Java with Stack (Accepted solution)


  • 0
    S
    import java.util.Stack;
    
    class Solution {
        public int calPoints(String[] ops) {
            
            int sum = 0;
            Stack<String> myStack = new Stack<String>();
            
            for(String element:ops)
            {
                if(element.equals("C"))
                {
                    String popStr =myStack.pop();
                    sum -= Integer.parseInt(popStr);
                }
                else if(element.equals("D"))
                {
                    String lastPoint = myStack.peek();
                    Integer curPoint = Integer.parseInt(lastPoint) * 2;
                    sum += curPoint;
                    myStack.push(String.valueOf(curPoint));
                    
                }
                else if(element.equals("+"))
                {
                    String l1 = myStack.pop();
                    String l2 = myStack.pop();
                    myStack.push(l2);
                    myStack.push(l1);
                    Integer curPoint = Integer.parseInt(l1) + Integer.parseInt(l2);
                    sum += curPoint;
                    myStack.push("" + curPoint);
                }
                else
                {
                    myStack.push(element);
                    sum += Integer.parseInt(element);
                }
                
            }
            
            
            
            
            
            return sum;
            
        }
    }
    

Log in to reply
 

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