Java solution use stack


  • 8
    Z
    public int calculate(String s) {
        int res =0,val=0;
        int sign = 1;
        Stack<Integer> st = new Stack<Integer>();
        s.trim();
        for(int i=0;i<s.length();i++){
            if(s.charAt(i) == '('){
                st.push(sign);
            }else if(s.charAt(i) == ')'){
                st.pop();
            }else if(s.charAt(i) == '+' || s.charAt(i) == '-'){
                res += sign*val;
                val = 0;
                if(!st.isEmpty()) {
                    sign = s.charAt(i) =='-'?st.peek()*(-1):st.peek();
                }else {
                    sign = s.charAt(i) =='-'?-1:1;
                }
            }else if(s.charAt(i) !=' '){
                val = val*10 + (s.charAt(i)-'0');
            }
        }
        res += val*sign;
        return res;
    }

  • 0
    H

    good
    but should it be s = s.trim()


Log in to reply
 

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