Java Solution with Stack and Regex


  • 0
    X
    class Solution {
        public int calPoints(String[] ops) {
            int sum = 0;
            if (ops == null || ops.length == 0) {
                return sum;
            }
            
            Stack<Integer> stack = new Stack<Integer>();
            
            for (int i = 0; i < ops.length; i++) {
                if (ops[i].matches("-?[0-9]+")) {
                    stack.push(Integer.parseInt(ops[i]));
                    sum += stack.peek();
                } else if (ops[i].equals("+")) {
                    int a = stack.pop();
                    int b = stack.peek();
                    stack.push(a);
                    stack.push(a + b);
                    sum += stack.peek();
                } else if (ops[i].equals("D")) {
                    stack.push(stack.peek() * 2);
                    sum += stack.peek();
                } else if (ops[i].equals("C")) {
                    sum -= stack.pop();
                }
            }
            return sum;
        }
    }
    

Log in to reply
 

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