Simple two pass java solution use stack


  • 0
    C

    I am very sure about how to mark the code area... the new system is not so convenient for users, right? I tried 5 mins to find the code button similar to the previous version, but failed, could anybody tell me how to mark it ?

    anyway, here I will explain my version. It's different from others. It's a two pass version. very straightforward.
    use two stack to store numbers and operator separately, in the first pass, when we meet a number which previous operator is * or / , compute them and push the value into the numbers stack.
    We can get the result from the second pass since all the operators are either + or - which is quite simple.

    
    public class Solution {
        public int calculate(String s) {
        int[] res = new int[2];
        res = helper(s,0);
        return res[0];
        
    }
    public int[] helper(String s,int start){
        int[] res = new int[2];
        int ans = 0;
        int i = start;
        int sign = 1;
        int lastnum = 0;
        while(i<s.length()){
            if(s.charAt(i)-'0'>=0&&s.charAt(i)-'0'<=9){
                int number = 0;
                while(i<s.length()&&s.charAt(i)-'0'>=0&&s.charAt(i)-'0'<=9){
                    number = 10*number + s.charAt(i) - '0';
                    i++;
                }
                ans+=sign*number;
                continue;
            }
            if(s.charAt(i) == ' '){
                i++;
                continue;
            }
            if(s.charAt(i) == '+'){
                sign = 1;
                i++;
                continue;
            }
            if(s.charAt(i) == '-'){
                sign = -1;
                i++;
                continue;
            }
            if(s.charAt(i) == '('){
                int[] temp = new int[2];
                temp = helper(s,i+1);
                ans+=sign*temp[0];
                i = temp[1] + 1;
                continue;
            }
            if(s.charAt(i)==')'){
                res[0] = ans;
                res[1] = i;
                return res;
            }
        }
        res[0] = ans;
        res[1] = i;
        return res;
    }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.