public class BaseballGame {
        public static int calPoints(String[] ops) {
            Deque<Integer> stack = new ArrayDeque<>();int sum = 0;
            for(String op: ops){
                if(op.equals("D")){
                    stack.push(stack.peek() * 2);
                    sum += stack.peek();
                }else if(op.equals("C")){
                    sum -= stack.peek();
                    stack.pop();

                }else if(op.equals("+")){
                    int cur = stack.peek();
                    stack.pop();
                    int pre = stack.peek();
                    stack.push(cur);
                    stack.push(cur + pre);
                    sum += stack.peek();
                }else{
                    stack.push(Integer.parseInt(op));
                    sum += stack.peek();
                }
            }
            return sum;
        }

    public static void main(String[] args) {
        String[] ops = {"5","2","C","D","+"};
        int res = calPoints(ops);
        System.out.println(res);
    }

}

在第一次看到题目的时候,下意识想到遍历,卡壳。看了讨论意识到需要使用stack。

以及,使用Deque<Integer> stack = new ArrayDeque<>();

Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack class.

posted on 2022-04-10 19:53  黎酒  阅读(39)  评论(0)    收藏  举报