Java Solution,Stack


  • 0
    L
       public int calPoints(String[] ops) {
            int result=0;
            Stack<Integer> stack=new Stack<>();
            for (int i = 0; i < ops.length; i++) {
                int points=0;
                if(ops[i].equals("C")){
                    if(!stack.isEmpty()){
                        points=-stack.pop();
                    }
                }else if(ops[i].equals("D")){
                    if(!stack.isEmpty()){
                        points=stack.peek()*2;
                        stack.push(points);
                    }
                }else if(ops[i].equals("+")){
                    if(stack.size()>1){
                        points=stack.elementAt(stack.size()-1)+stack.elementAt(stack.size()-2);
                        stack.push(points);
                    }
                }else{
                    points=Integer.valueOf(ops[i]);
                    stack.push(points);
                }
                result+=points;
            }
            return result;
        }
    

Log in to reply
 

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