My java solution with one stack.


  • 0
    Y

    The idea is to expand the formula and use a stack to keep track of signs which are in front of each "(". Then calculate the sign of each number and sum them up.

    public class Solution {
    public int calculate(String s) {
        Stack<Character> stack=new Stack<>();
        int i=0,sign=1,res=0;
        while(i<s.length()){
            if(s.charAt(i)==' ') i++;
            else if(s.charAt(i)=='('){
                if(i>0) stack.push(s.charAt(i-1));
                if(!stack.isEmpty()&&stack.peek()=='-') sign=-sign;
                i++;
            }
            else if(s.charAt(i)==')'){
                if(!stack.isEmpty()&&stack.pop()=='-') sign=-sign;
                i++;
            }
            else{
                int j=Character.isDigit(s.charAt(i))?i:i+1,p=0;
                while(j<s.length()&&Character.isDigit(s.charAt(j))){
                   p=10*p+s.charAt(j)-'0';
                   j++; 
                } 
                res+=(s.charAt(i)=='-'?-1:1)*sign*p;
                i=j;
            }
        }
        return res;
    }
    

    }


Log in to reply
 

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