Skip to content

Latest commit

 

History

History
58 lines (46 loc) · 2.77 KB

풀이_LC682.md

File metadata and controls

58 lines (46 loc) · 2.77 KB

👻 682. Baseball Game

  • Date : 2021.10.31(일)
  • Time : 20분

Problem

  • You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.
  • At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following:
    1. An integer x - Record a new score of x.
    2. "+" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
    3. "D" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
    4. "C" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.
  • Return the sum of all the scores on the record.

Constraints

  • 1 <= ops.length <= 1000
  • ops[i] is "C", "D", "+", or a string representing an integer in the range [-3 * 10^4, 3 * 10^4].
  • For operation "+", there will always be at least two previous scores on the record.
  • For operations "C" and "D", there will always be at least one previous score on the record.

Example

  • 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.
    



풀이

    def calPoints(self, ops: List[str]) -> int:
        score = []
        for i in range(len(ops)):
            if ops[i] == 'C':
                score.pop()
            elif ops[i] == 'D':
                score.append(2 * score[-1])
            elif ops[i] == '+':
                score.append(score[-1] + score[-2])
            else:
                score.append(int(ops[i]))
        return sum(score)
    
        

: 이 문제는 3개의 점수 조건이 존재한다. 그리고 모든 연산은 이전 점수가 존재한다는 조건이 있다(첫 게임이 아니라는 뜻). 먼저 C는 이전 점수를 무효화 하는 것이기 때문에 stack에서 pop을 통해 자동으로 마지막 index에 존재하는 점수를 없애주었다. 혹은 [:-1]로 슬라이싱도 가능할 것 같다. 그리고 D는 이전 점수 2배를 저장하는 것이기 때문에 [-1] 을 통해 마지막 점수를 가져와서 *2를 해주었다. 그리고 append를 통해 자동으로 stack의 마지막 부분에 점수를 쌓아준다. 그리고 세번재는 +인데, +는 뒤의 2개 점수를 더해주면 된다.