Java Solution w/Stack (O(n))


  • 0
    S

    The idea is to use a stack to hold the most recent valid moves.

    class Solution {
        public int calPoints(String[] ops) {
            int pts = 0;   
            Stack<Integer> rounds = new Stack<>();
            
            for (int i = 0; i < ops.length; i++) {
                String s = ops[i];
                
                if (s.equals("C")) {
                    int last = rounds.pop();
                    pts -= last;
                } else if (s.equals("D")) {
                    int last = rounds.peek();
                    int num = last*2;
                    pts += num;
                    rounds.push(num);
                } else if (s.equals("+")) {
                    int prev = rounds.pop();
                    int num = prev + rounds.peek();
                    pts += num;
                    rounds.push(prev);
                    rounds.push(num);
                } else {
                    int num = Integer.parseInt(s);
                    pts += num;
                    rounds.push(num);
                }
            }
            return pts;
        }
    }
    

Log in to reply
 

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