408算法练习——比赛计分

比赛记分员

一、问题描述

  你是一名记分员,现按照如下规则计分

  如果该字符为数字,表示当轮比赛的得分情况

  如果字符是“+”,表示当轮比赛得分为上两轮之和

  如果字符是“C”,代表上一轮得分无效

  如果字符是“D”,代表当轮比赛得分是上一轮的二倍

  求最后总得分并返回。输入为一个字符串数组ops,下标为回合数

  样例:
  

 

   说明:

    0:本回合得分为5

    1:本回合得分为2

    2:上回合得分无效,本回合不计分

    3:本回合得分为上回合2倍=10

    4:本回合得分为前两回合相加:10+5=15(2回合未计分,1回合被取消,所以是0回合加3回合)

  总得分为5+10+15

二、解题思路

    可以使用一个栈记录每回合的得分,遍历数组的过程中遇到C就将栈顶弹出,遇到数组就进栈,遇到D就将栈顶元素的二倍压入栈,遇到+就提取栈顶两个元素的值作加法后入栈。

三、代码

注意:本段代码为java代码,但是思想与C++一致,本人C++菜鸟,写的不熟练就改用Java实现

 1 public int countScore(String[] str) {
 2         Stack<Integer> stack = new Stack<Integer>();
 3         int count = 0;
 4         for(int i=0;i<str.length;i++) {
 5             if(str[i].equals("C")||str[i].equals("c")) {
 6                 stack.pop();
 7             }else if(str[i].equals("D")||str[i].equals("d")) {
 8                 int nele = 2*stack.peek();
 9                 stack.push(nele);
10             }else if(str[i].equals("+")) {
11                 int rback = stack.pop();
12                 int nele = rback+stack.peek();
13                 stack.push(rback);
14                 stack.push(nele);
15             }else {
16                 stack.push(Integer.parseInt(str[i]));
17             }
18         }
19         while(!stack.empty()) {
20             count += stack.pop();
21         }
22         return count;
23     }

 

posted @ 2021-07-06 20:48  瑜琦  阅读(264)  评论(0)    收藏  举报