772. Basic Calculator III

54 阅读1分钟

image.png

image.png

方法

class Solution {
    public int calculate(String s) {
        int res = 0;
        Stack<Integer> stack = new Stack<>();
        char[] arr = s.toCharArray();
        int val = 0;
        char op = '+';
        for (int i = 0; i < arr.length; i++) {
            char c = arr[i];
            if (c == '(') {
                int count = 1;
                int cur = i + 1;
                while (count != 0) {
                    if (arr[cur] == ')') {
                        count--;
                    }
                    if (arr[cur] == '(') {
                        count++;
                    }
                    cur++;
                }
                // 找到了对应的括号,递归解决
                val = calculate(s.substring(i + 1, cur - 1));
                i = cur - 1;
            }
            if (Character.isDigit(c)) {
                val = val * 10 + c - '0';
            }
            if (!Character.isDigit(c) || i == arr.length - 1) {
                if (op == '+') {
                    stack.push(val);
                } else if (op == '-') {
                    stack.push(-val);
                } else if (op == '*') {
                    stack.push(stack.pop() * val);
                } else if (op == '/') {
                    stack.push(stack.pop() / val);
                }
                val = 0; // 
                op = c;
            }
        }

        while (!stack.isEmpty()) {
            res += stack.pop();
        }

        return res;
    }
}