224. Basic Calculator

49 阅读1分钟

image.png

方法 o(n)

(1 + 3 - (4-5+6))

+(1 + 3 - (4-5+6))

  • thinking of the process of removing the ()
  • if outer is +, then inner sign do not need to be changed
  • if outer is -, then inner sign do not need to be reversed
  • stack stores the sign of current level/parentheses
class Solution {
    public int calculate(String s) {
        int res = 0;
        char[] arr = s.toCharArray();
        Stack<Integer> stack = new Stack<>();// 存每一层的符号
        int sign = 1; // 最外层的是+,把s考虑为 +(s)
        stack.push(sign);
        for (int i = 0; i < arr.length; i++) {
            if (Character.isDigit(arr[i])) {
                int j = i;
                int val = 0;
                // 累积计算数字
                while (j < arr.length && Character.isDigit(arr[j])) {
                    val = val * 10 + (arr[j] - '0');
                    j++;
                }
                i = j - 1;
                res += sign * val;
            } else if (arr[i] == '+') {
                sign = stack.peek(); // 括号内部的符号,不需要变
            } else if (arr[i] == '-') {
                sign = -stack.peek();// 括号内部的符号,需要变,因为外层为-
            } else if (arr[i] == '(') {
                stack.push(sign); // 一层开始
            } else if (arr[i] == ')') {
                stack.pop(); // 一层结束
            }
        }

        return res;
    }
}