Java Stack Solution


  • 0
    M
    class Solution {
        public int calPoints(String[] ops) {
            Stack<Integer> validPoints = new Stack<Integer>();
            int totalSum = 0;
            
            for(String operation : ops){
                if(operation.equals("C")){
                    Integer invalidatePoint = validPoints.pop();
                    totalSum = totalSum - invalidatePoint; 
                }else if(operation.equals("D")){
                    Integer lastValidPoint = validPoints.peek();
                    Integer thisRoundPoints = 2 * lastValidPoint;
                    validPoints.push(thisRoundPoints);
                    totalSum += thisRoundPoints;
                }else if(operation.equals("+")){
                    Integer lastRoundValidPoints = validPoints.pop();
                    Integer currentRoundPoints = lastRoundValidPoints + validPoints.peek();
                    validPoints.push(lastRoundValidPoints);
                    validPoints.push(currentRoundPoints);
                    totalSum += currentRoundPoints;
                }else{
                    Integer validPoint = Integer.valueOf(operation);
                    validPoints.push(validPoint);
                    totalSum += validPoint;
                }
            }
         
            return totalSum;
        }
    }
    

Log in to reply
 

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