【数据结构】算法 Baseball Game 棒球比赛

Baseball Game 棒球比赛

比赛开始时,记录是空白的。你会得到一个记录操作的字符串列表 ops,其中 ops[i] 是你需要记录的第 i 项操作,ops 遵循下述规则:

整数 x - 表示本回合新获得分数 x
"+" - 表示本回合新获得的得分是前两次得分的总和。题目数据保证记录此操作时前面总是存在两个有效的分数。
"D" - 表示本回合新获得的得分是前一次得分的两倍。题目数据保证记录此操作时前面总是存在一个有效的分数。
"C" - 表示前一次得分无效,将其从记录中移除。题目数据保证记录此操作时前面总是存在一个有效的分数
Return the sum of all the scores on the record.

Input: ops = ["5","2","C","D","+"]
Output: 30
Explanation:
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.

思路

说的很明白,计分的规则如上,数组里面如果存放的是每一个回合的分数,直接sum就好了,一点问题都没有,但是这个eggache的规则并不会直接告诉我们分数。只是说每回合的分数可能是数字,或者是其他字符 CD+,C影响的不仅是本轮而且包括上一次,D是表示本次分数是前1次的double,+ 是前2次的sum。

没错就是用Stack,每一次的处理都会将其他字符转成num

public int calPoints(String[] ops) {
        Stack<Integer> s = new Stack<Integer>();
        for (int i = 0; i < ops.length; i++){
            if(ops[i].equals("+")){
                Integer a = s.pop();
                int b = s.peek();
                s.push(a);
                s.push(a+b);
            }
            else if(ops[i].equals("D")){
                Integer peek = s.peek();
                s.push(peek*2);
            }
            else if(ops[i].equals("C")){
                s.pop();
            }
            else{
                s.push(Integer.valueOf(ops[i]));
            }
        }
        int score = 0;
        while (!s.isEmpty()){
            score+= s.pop();
        }
        return  score;
    }

Tag

Stack

原文地址:https://www.cnblogs.com/dreamtaker/p/14587871.html