224. 基本计算器

class Solution {
    int index = 0;
    public int calculate(String s) {
        int n = s.length();
        Stack<Integer> stack = new Stack();
        char pre = '+';
        int num = 0;
        for(; index < n; index ++) {
            char c = s.charAt(index);
            if(Character.isDigit(c)) {
                num = num * 10 + (c - '0');
            }
            if(c == '(') {
                index++;
                num = calculate(s);
            }    
            if(!Character.isDigit(c) && c != ' ' || index == n - 1) {
                switch(pre) {
                    case '+':
                        stack.push(num);
                        break;
                    case '-':
                        stack.push(-num);
                        break;
                    case '*':
                        stack.push(stack.pop() * num);
                        break;
                    case '/':
                        stack.push(stack.pop() / num);
                        break;
                }
                pre = c;
                num = 0;
            }
            if(c == ')') break;
            
        }
        int res = 0;
        while(!stack.empty()) {
            res += stack.pop();
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/yonezu/p/13504268.html