Array Iteration with Stacks . Java


  • 0
    G
    class Solution {
        public int calPoints(String[] ops) {
            Stack<Integer>stack = new Stack<Integer>();
            for(String i: ops){
                if(i.equals("D")){
                    if(!stack.isEmpty()){
                        stack.push(stack.peek()*2);
                    }
                }
                else if(i.equals("C")){
                     if(!stack.isEmpty()){
                        stack.pop();
                    }
                }
                else if(i.equals("+")){
                    if(!stack.isEmpty()){
                        int temp = stack.pop();
                        int temp2 = temp+stack.peek();
                        stack.push(temp);
                        stack.push(temp2);
                    }
                }
               else{
                   stack.push(Integer.parseInt(i));
               } 
            }
            int sum=0;
            while(!stack.isEmpty()){
                System.out.println(stack.peek());
                sum+=stack.pop();
            }
            return sum;
        }
    }
    

Log in to reply
 

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