My JAVA solution with stack


  • 0
    W
    class Solution {
        public int calPoints(String[] ops) {
            Stack<Integer> stack = new Stack<Integer>();
            int currSum = 0, current, i;
            for(i = 0; i < ops.length; i ++) {
                if(!ops[i].equals("C") && !ops[i].equals("D") && !ops[i].equals("+")) {
                    current = Integer.parseInt(ops[i]);
                    currSum += current;
                    stack.push(current);
                }
                else if(ops[i].equals("C")) {
                    int cancelled = stack.pop();
                    currSum -= cancelled;
                }
                else if(ops[i].equals("D")) {
                    int last = stack.peek();
                    current = 2 * last;
                    currSum += current;
                    stack.push(current);
                }
                else if(ops[i].equals("+")) {
                    int last = stack.peek();
                    int tmp = stack.pop();
                    int lasttwo = stack.peek();
                    stack.push(tmp);
                    current = last + lasttwo;
                    currSum += current;
                    stack.push(current);
                }
                else continue;
            }
            return currSum;
        }
    }
    

Log in to reply
 

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