682. 棒球比赛 java

题目: https://leetcode-cn.com/problems/baseball-game/description/

示例 1:

输入: ["5","2","C","D","+"]
输出: 30
解释: 
第1轮:你可以得到5分。总和是:5。
第2轮:你可以得到2分。总和是:7。
操作1:第2轮的数据无效。总和是:5。
第3轮:你可以得到10分(第2轮的数据已被删除)。总数是:15。
第4轮:你可以得到5 + 10 = 15分。总数是:30。

分析:

如果只有Integer、+和D的话这题就非常简单了,只用保存上两轮的得分,以及一个累加和就好了。但注意到这里
有C可以撤销上一轮的得分,并且C出现的次数没有限制,那么这里就必须用到栈来记录和管理之前每轮的得分了。

那么这题实际上就是对栈的操作了:

Integer:本轮得分为Integer,入栈。//Integer.parseInt()
+:本轮得分为当前两个栈顶值之和,入栈。//peek()+get(history.size() -2)
D:本轮得分为当前栈顶值的两倍,入栈。//peek()*2
C:栈顶出栈。 //pop()
最终结果为当前栈中所有值的和。

代码+测试例子

class Solution {
    public int calPoints(String[] ops) {
        Stack<Integer> history= new Stack<>();
        for(String op:ops){
            switch(op){
                case "+":
                    history.push(history.peek()+history.get(history.size() -2));
                    break;
                case "D":
                    history.push(history.peek()*2);
                    break;
                case "C":
                    history.pop();
                    break;
                default:
                    history.push(Integer.parseInt(op));
            }
        }
        int result = 0;
        for(int item:history){
            result +=item;
        }
        return result;
    }
}

 代码分析:

1) Integer.parseInt()  

字符串参数解析为带符号的十进制整数字符串中的字符必须都是十进制数字,除了第一个字符可以是ASCII减号{@code '-'} ({@code '\u005Cu002D'})来表示负数或ASCII加号{@code '+'}来表示正数。

2) peek,pop的用法,用了break后后面的就不执行了,进行下一个switch(op)

 参考:https://www.polarxiong.com/archives/LeetCode-682-baseball-game.html

猜你喜欢

转载自blog.csdn.net/nsjlive/article/details/82598580