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)

class Solution {
    public int calculate(String s) {
        s=s.replace(" ","")+'+';     //here add a '+' at the tail of the s!
        Stack<Integer> stk = new Stack<>();
        int num =0;
        char sign='+';
      
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(Character.isDigit(c)){
                num=num*10+c-'0';
            }
            else{
                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);
                }
                num=0;
                sign=c;
            }
        }
        
        int res =0;
        for(int i:stk){
            res+=i;
        }
        return res;
    }
}

 

posted on 2022-02-09 02:27  阳光明媚的菲越  阅读(18)  评论(0编辑  收藏  举报