Easy Java Solution Using Stack


  • 0
    
    class Solution {
        public int calPoints(String[] ops) {
            //keep track of valid points so far..
            Stack<Integer> stack = new Stack();
            for(String s : ops){
    
                if(s.equals("C")){
                    stack.pop();
                }
                else if( s.equals("D")){
                    stack.push(2* stack.peek());
                }
                else if(s.equals("+")){
                    int a = stack.pop();
                    int b = stack.pop();
                    int sum = a + b;
                    stack.push(b);
                    stack.push(a);
                    stack.push(sum); 
                }
                else{
                    stack.push(Integer.parseInt(s));
                }
            }
            
            int ans = 0;
            while(!stack.isEmpty()){
                ans += stack.pop();
            }
            return ans;
        }
    }

Log in to reply
 

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