Easy - 682. Baseball Game

Doyeon Kim·2022년 8월 12일

코딩테스트 공부

목록 보기
103/171

문제 링크 : https://leetcode.com/problems/baseball-game/


배열 ops가 주어졌을 때 아래와 같은 규칙이 주어진 후, 이후 최종 합을 구하는 문제이다.

An integer x - Record a new score of x.
"+" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
"D" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
"C" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.

해당 규칙에따라 구현하고 빈 스택을 만들어 이에 append한 뒤 결과를 합하면 되는 어렵지 않은 문제였다.

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

22.10.13 복습

profile
성장하고 도전하는 개발자. 프로그래밍 좋아하세요?

0개의 댓글