Java, calculate weight for each parenthesis pairs


  • 0
    R
    class Solution {
        public int calculate(String s) {
            
            char operator = '+';
            Stack<Integer> weightStack = new Stack<>();
            weightStack.push(1);    
            
            int sum = 0;
            
            // 3-(1-2-(3+1))
            //  -1   -1*-1    ()  weight = prevWeight * (if '-' -1 else 1)  stack()
            
            // 3-(3+1-(2+3))    3-3-1+2+3
            
            for(int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if(isDigit(c)) {
                    int start = i;
                    while(i+1 < s.length() && isDigit(s.charAt(i+1)))   i++;
                    int currentNum = Integer.valueOf(s.substring(start, i+1));
                    if(operator == '+') {
                        sum += weightStack.peek()*currentNum;
                    }
                    else if(operator == '-') {
                        sum -= weightStack.peek()*currentNum;
                    }
                }
                else if(c == '(') {
                    if(operator == '-') {
                        operator = '+';    //  -(4+5)
                        weightStack.push(weightStack.peek()*(-1));
                    }
                    else if(operator == '+') {
                        weightStack.push(weightStack.peek()*1);
                    }
                }
                else if(c == ')') {
                    weightStack.pop();
                }
                else if(c == '+' || c == '-') {
                    operator = c;
                }
            }
            
            return sum;
        }
        
        public boolean isDigit(char c) {
            return c <= '9' && c >= '0';
        }
    }
    

Log in to reply
 

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