LeetCode 682 Baseball Game 解题报告

时间:2023-03-09 19:49:32
LeetCode 682 Baseball Game 解题报告

题目要求

You're now a baseball game point recorder.

Given a list of strings, each string can be one of the 4 following types:

  1. Integer (one round's score): Directly represents the number of points you get in this round.
  2. "+" (one round's score): Represents that the points you get in this round are the sum of the last two valid round's points.
  3. "D" (one round's score): Represents that the points you get in this round are the doubled data of the last valid round's points.
  4. "C" (an operation, which isn't a round's score): Represents the last validround's points you get were invalid and should be removed.

Each round's operation is permanent and could have an impact on the round before and the round after.

You need to return the sum of the points you could get in all the rounds.

题目分析及思路

题目规定了四种字符:整数字符即是这一轮的所得分数,‘+’表示该轮分数是前两轮有效分数的和,‘D’表示该轮分数是前一轮有效分数的翻倍,‘C’表示上轮分数无效。最后给出所有轮数结束后的总得分。可以遍历每个字符,对每个字符做条件判断,将有效分数存在一个列表里。最后返回列表的和。

python代码

class Solution:

def calPoints(self, ops: List[str]) -> int:

res = []

for op in ops:

if op == 'C':

res.pop()

elif op == '+':

res.append(res[-1] + res[-2])

elif op == 'D':

res.append(2 * res[-1])

else:

res.append(int(op))

return sum(res)