227. Basic Calculator II

要注意的就是我们在处理每个数字结果之前,都已经确定了它前面有的sign。

class Solution {
    public int calculate(String s) {
        if (s == null || s.length() == 0){
            return 0;
        }
        //"3+2*2"
        //stack: 4 3
        //num:2
        s = s.replaceAll(" ","");//does this line of code has effect on time complexity?
        int res = 0;
        char sign = '+';
        int num = 0;
        Stack stack = new Stack<>();
        for (int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            if (Character.isDigit(c)){
                num = c - '0';
                while (i + 1 < s.length() && Character.isDigit(s.charAt(i+1))){
                    num = num*10 + s.charAt(i+1) - '0';
                    i++;
                }
            } 
            if (!Character.isDigit(s.charAt(i)) || i == s.length() - 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 = s.charAt(i);
                num = 0;
            }
        }
        for (int i : stack){
            res += i;
        }
        return res;
    }
}

你可能感兴趣的:(227. Basic Calculator II)