首页 > 代码库 > 224. Basic Calculator

224. Basic Calculator

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

Note: Do not use the eval built-in library function.


 

一般是无法顺序执行、有些数据无法处理、需要回头再来处理时用到栈。在这个计算器中,如果只有‘+’,‘-‘运算,可以顺序执行。碰到(),需要把括号里整个表达式算出来,因此对()要用栈来处理。

对含有+ - * /的运算符,因为* /的优先级高于+ -,碰到了* /,前一个运算符若是+ 或者-,它需要延迟计算,因此对所有都要用到栈。

public class Solution {
    public int calculate(String s) {
        Stack<Integer> nums = new Stack<Integer>();
        Stack<Character> ops = new Stack<Character>();
        int re = 0, num = 0;
        char op = ‘+‘;
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
                case ‘+‘:
                case ‘-‘:
                    if (op == ‘+‘) {
                        re = re + num;
                    } else {
                        re = re - num;
                    }
                    num = 0;
                    op = s.charAt(i);
                    break;
                case ‘(‘:
                    nums.push(re);
                    ops.push(op);
                    re = 0;
                    op = ‘+‘;
                    break;
                case ‘)‘:
                    if (op == ‘+‘) {
                        re = re + num;
                    } else {
                        re = re - num;
                    }
                    num = 0;
                    char c = ops.pop();
                    int prev = nums.pop();
                    if (c == ‘+‘) {
                        re = prev + re;
                    } else {
                        re = prev - re;
                    }
                    break;
                case ‘ ‘:
                    break;
                default:
                    num = 10 * num + s.charAt(i) - ‘0‘;
            }
        }
        if (num != 0) {
            if (op == ‘+‘) {
                return re + num;
            } else {
                return re - num;
            }
        }
        return re;
    }
}

 

224. Basic Calculator