Java Solution


  • 0
    V

    class Solution {
    public int calculate(String s) {
    int[] rst = calculateHelper(0, s);
    return rst[1];
    }

    private int[] calculateHelper(int startIndex, String s) {
        Stack<String> stack = new Stack<String>();
        int num = -1;
        
        while (startIndex < s.length()) {
            Character c = s.charAt(startIndex);
            
            if (c == '+' || c == '-') {
                if (num != -1) {
                    processNum(stack, num);
                    num = -1;
                }
                stack.push(c + "");
            } else if (c - '0' >= 0 && c - '0' <= 9) {
                num = num == -1 ? c - '0' : num*10 + c - '0';   
            } else if (c == '(') {
                if (num != -1) {
                    processNum(stack, num);
                    num = -1;
                }
                
                int[] rst = calculateHelper(startIndex + 1, s);
                processNum(stack, rst[1]);
                startIndex = rst[0];
            } else if (c == ')') {
                if (num != -1) {
                    processNum(stack, num);
                    num = -1;
                }
                
                int[] rst = new int[2];
                rst[0] = startIndex;
                rst[1] =  Integer.parseInt(stack.pop());
                return rst;
            }
            
            startIndex++;
        }
        
        
        int[] rst = new int[2];
        rst[0] = s.length();
        if (!stack.isEmpty()) {
              if (num != -1) {
                    processNum(stack, num);
                    num = -1;
               }
            rst[1] =  Integer.parseInt(stack.pop());
        } else {
            rst[1] = num;
        }
        
        return rst;
    }
    
    private void processNum(Stack<String> stack, int num) {
        if (!stack.isEmpty()) {
                if (stack.peek().equals("+")) {
                    stack.pop();
                    int priorNum = Integer.parseInt(stack.pop());
                    int plusRst = priorNum + num;
                    stack.push(Integer.toString(plusRst));
                } else if (stack.peek().equals("-")) {
                    stack.pop();
                    int priorNum = Integer.parseInt(stack.pop());
                    int divRst = priorNum - num;
                    stack.push(Integer.toString(divRst));
                }
        } else {
            stack.push(Integer.toString(num));
        }
    }
    

    }


Log in to reply
 

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