682. Baseball Game

原题:https://leetcode.com/problems/baseball-game/description/
大意:这道题初一看没看懂意思,其实很简单

  • Integer (one round’s score): Directly represents the number of points you get in this round.
  • “+” (one round’s score): Represents that the points you get in this round are
    the sum of the last two valid round’s points.
  • “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.
  • “C” (an operation, which isn’t a round’s score): Represents the last valid round’s points you get were invalid and should be removed.

翻译成中文就是:

  • 数字(得分轮):本轮的得分为该数字
  • “+” (得分轮): 本轮的得分为前两个有效数字之和
  • “D”(得分轮): 本轮的得分为前一个有效数字的双倍
  • “C” (操作轮):去掉上一个有效数字

这一看前一个上一个的,自然而然想到了栈操作。但是python是没有现成的栈对象可以使用的,用list将就一下也能用

class Solution:
    def calPoints(self, ops):
        """
        :type ops: List[str]
        :rtype: int
        """
        stack = []
        for string in ops:
            if string == 'C':
                stack.pop()
            elif string == 'D':
                if stack:
                    stack.append(stack[-1] * 2)
            elif string == '+':
                if len(stack) >= 2:
                    stack.append(stack[-1] + stack[-2])
            else:
                stack.append(int(string))

        return sum(stack)

a = Solution()
print (a.calPoints(["5","2","C","D","+"]))

知识点:

我们可以在python中人为新建一个类,模拟栈操作,具体请看我的另一篇
Python中的栈

    原文作者:fred_33c7
    原文地址: https://www.jianshu.com/p/99bf6deb6060
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞