java easy solution, Stack


  • 0
    Z
    class Solution {
        public int calPoints(String[] ops) {
            int sum = 0;
            Stack<Integer> stack = new Stack<>();
            for(String op:ops){
                if("C".equals(op)){
                    sum -= stack.pop();
                }else if("D".equals(op)){
                    int temp = 2*stack.peek();
                    sum += temp;
                    stack.push(temp);
                }else if("+".equals(op)){
                    int temp1 = stack.pop();
                    int temp2 = stack.peek();
                    int temp3 = (temp1+temp2);
                    sum += temp3;
                    stack.push(temp1);
                    stack.push(temp3);
                }else{
                    Integer point = Integer.parseInt(op);
                    stack.push(point);
                    sum += point;
                }
            }
            return sum;
        }
    }
    

Log in to reply
 

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