zoukankan      html  css  js  c++  java
  • 【数据结构】算法 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

  • 相关阅读:
    在实体属性上通过注解格式化日期
    @Validated和@Valid区别:Spring validation验证框架对入参实体进行嵌套验证必须在相应属性(字段)加上@Valid而不是@Validated
    两种根据关键字查询的方法SQL
    excel批量导入数据
    下载excel模板
    上传人员照片
    身份证校验类
    把字符串参数分割成数组 传入SQL foreach遍历查询
    使用Hibernate-Validator优雅的校验参数
    如何使用Graphics2D在一张图片上画线(包括箭头)
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14587871.html
Copyright © 2011-2022 走看看