Problem 227

Posted by Ruizhi Ma on October 26, 2020

Solution URL

https://leetcode.com/submissions/detail/413535598/

代码

class Solution {
    public int calculate(String s) {
        //ans: https://leetcode-cn.com/problems/basic-calculator-ii/submissions/
        //Time: O(N)
        //Space: O(N)
        Stack<Integer> stack = new Stack<>();
        //去除首尾空格
        s = s.trim();
        char[] c = s.toCharArray();
        char operator = '+';
        int num = 0;

        for(int i = 0; i < c.length; i++){
            if(c[i] == ' ') continue;

            if(Character.isDigit(c[i])){
                num = num * 10 + c[i] - '0';
            }

            //最后一位的时候,还有操作符没处理
            if(!Character.isDigit(c[i]) || i == c.length - 1){
                //此时已经到下一次操作符,要先将之前的运算处理掉
                if(operator == '+'){
                    stack.push(num);
                }else if(operator == '-'){
                    stack.push(-num);
                }else if(operator == '*'){
                    int a = stack.pop();
                    stack.push(a * num);
                }else if(operator == '/'){
                    int a = stack.pop();
                    stack.push(a / num);
                }

                operator = c[i];//保存当前操作符
                num = 0;//还原num
            }
        }

        int sum = 0;
        while(!stack.isEmpty()){
            sum += stack.pop();
        }

        return sum;
    }
}