0
点赞
收藏
分享

微信扫一扫

LeetCode 682. 棒球比赛

微言记 2022-03-26 阅读 80
leetcode

题目链接:

力扣icon-default.png?t=M276https://leetcode-cn.com/problems/baseball-game/

【分析】用栈来模拟就行,当然不用栈,开一个1001长度的数组也可以。

class Solution {
    public int calPoints(String[] ops) {
        Stack<Integer> stack = new Stack<>();
        int n = ops.length, i, a, b;
        String str;
        for(i = 0; i < n; i++){
            str = ops[i];
            if(str.equals("+")){
                a = stack.pop();
                b = stack.peek();
                stack.push(a);
                stack.push(a + b);
            }else if(str.equals("D")){
                stack.push(stack.peek() * 2);
            }else if(str.equals("C")){
                stack.pop();
            }else{
                stack.push(Integer.parseInt(str));
            }
        }
        int ans = 0;
        while(!stack.empty()){
            ans += stack.pop();
        }
        return ans;
    }
}

 

 

举报

相关推荐

0 条评论