682 baseball game

AC and Best Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def (self, ops):
"""
:type ops: List[str]
:rtype: int
"""
obj = [0,[]]
for i in ops:
if i == "C":
last = obj[1].pop()
obj[0] -= last
elif i == "D":
obj[1].append(obj[1][-1]*2)
obj[0] += obj[1][-1]
elif i == "+":
obj[1].append(obj[1][-1]+obj[1][-2])
obj[0]+= obj[1][-1]
else:
obj[1].append(int(i))
obj[0] += obj[1][-1]
return obj[0]

Time complexity:O(n)
Space complexity: O(2)

keep a stack to record score change and a sum for current sum
when a new operation happen, update the stack and the sum