`

Leetcode - Basic Calculator II

 
阅读更多
mplement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
Note: Do not use the eval built-in library function.

[分析]
思路1: 将输入先转换为逆波兰表达式,然后计算逆波兰表达式。该类型题目标准解法。
思路2:参考https://leetcode.com/discuss/41902/share-my-java-solution
特别注意代码中的这个条件:if (!Character.isDigit(c) && c != ' ' || i == len - 1)
算法的思路是先解析一个新的运算数,然后判断其前面的运算符,若是乘除则立即算出结果放入栈中,若是正负号则与当前数字结合加入栈中,最后栈中数累加即为结果。

public class Solution {
    // Method 2
    public int calculate(String s) {
        if (s == null || s.length() == 0)
            return 0;
        List<String> revPolish = reversePolish(s);
        return evalRPN(revPolish);
    }
    public List<String> reversePolish(String s) {
        List<String> tokens = new ArrayList<String>();
        LinkedList<Character> signs = new LinkedList<Character>();
        for (int i = 0; i < s.length(); i++) {
            int j = i;
            int num = 0;
            while (i < s.length() && '0' <= s.charAt(i) && s.charAt(i) <= '9') {
                num = num * 10 + s.charAt(i) - '0';
                i++;
            } 
            if (j < i) tokens.add(String.valueOf(num));
            if (i == s.length()) break;
            char c = s.charAt(i);
            if (c == '+' || c == '-') {
                while (!signs.isEmpty()) {
                    tokens.add(String.valueOf(signs.pop()));
                }
                signs.push(c);
            } else if (c == '*' || c == '/') {
                while (!signs.isEmpty() && (signs.peek() == '/' || signs.peek() == '*')) {
                    tokens.add(String.valueOf(signs.pop()));
                }
                signs.push(c);
            }
        }
        while (!signs.isEmpty())
            tokens.add(String.valueOf(signs.pop()));
        return tokens;
    }
    public int evalRPN(List<String> tokens) {
        LinkedList<Integer> nums = new LinkedList<Integer>();
        for (int i = 0; i < tokens.size(); i++) {
            String curr = tokens.get(i);
            if (curr.equals("+")) {
                int num2 = nums.pop(), num1 = nums.pop();
                nums.push(num1 + num2);
            } else if (curr.equals("-")) {
                int num2 = nums.pop(), num1 = nums.pop();
                nums.push(num1 - num2);
            } else if (curr.equals("*")) {
                int num2 = nums.pop(), num1 = nums.pop();
                nums.push(num1 * num2);
            } else if (curr.equals("/")) {
                int num2 = nums.pop(), num1 = nums.pop();
                nums.push(num1 / num2);
            } else {
                nums.push(Integer.parseInt(curr));
            }
        }
        return nums.pop();
    }
    // Method 1
    public int calculate1(String s) {
        if (s == null) return 0;
        LinkedList<Integer> stack = new LinkedList<Integer>();
        char sign = '+';
        int num = 0;
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c))
                num = num * 10 + c - '0';
            if (!Character.isDigit(c) && c != ' ' || i == len - 1) {
                if (sign == '+') stack.push(num);
                else if (sign == '-') stack.push(-num);
                else if (sign == '*') stack.push(stack.pop() * num);
                else if (sign == '/') stack.push(stack.pop() / num);
                sign = c;
                num = 0;
            }
        }
        int res = 0;
        while (!stack.isEmpty())
            res += stack.pop();
        return res;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics