227. Basic Calculator II

For this problem, we must know the sign just before the num. For example, s = "3+2*2", when we deal with the first 2, we must know '+' is just before it, when we deal with the second 2, we must know '*' is just before it.

According to the sing before the num, we can decide whether push them to the stack directly or pop the stack and then push back.

The solution is as following, the time complexity is O(n)

    public int calculate(String s) {
        s = s.replace(" ", "");
        Stack<Integer> stk = new Stack<>();
        int num = 0;
        int sign = '+';
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(Character.isDigit(c)){
                num = num*10+c-'0';
            }
            if(!Character.isDigit(c)||i==s.length()-1){
                if(sign=='+'){
                    stk.push(num);
                }else if(sign=='-')
                    stk.push(-num);
                else if(sign=='*')
                    stk.push(stk.pop()*num);
                else if(sign=='/')
                    stk.push(stk.pop()/num);
                sign = c;
                num=0;
            }
        }
        int res = 0;
        for(int i: stk)
            res+=i;
        return res;
        
    }

 

上一篇:JMM之happens-before整理


下一篇:Spring Security注解@PreAuthorize与AOP切面执行顺序