这道题跟227题,背下来!

 Iterative:

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

 

Recursive:

class Solution {
    public int calculate(String s) {
        s=s.replace(" ", "");
        Queue<Character> queue = new LinkedList<>();
        for(int i=0;i<s.length();i++){
            queue.offer(s.charAt(i));
        }
        return helper(queue);
    }
    
    private int helper(Queue<Character> queue){
        Stack<Integer> stk = new Stack<>();
        int num =0;
        int sign=1;
        int res = 0;
        while(!queue.isEmpty()){
            char c = queue.poll();
            if(Character.isDigit(c)){
                num=num*10+c-'0';
            }else{
                if(c=='+'){
                    res+=sign*num;
                    num=0;
                    sign=1;
                }
                else if(c=='-'){
                    res+=sign*num;
                    num=0;
                    sign=-1;
                }else if(c=='('){
                    res+=sign*helper(queue);
                }else {
                    break;
                }
            }
        }
        return res+sign*num;
    }
}

 

posted on 2022-03-29 13:12  阳光明媚的菲越  阅读(21)  评论(0编辑  收藏  举报