150. Evaluate Reverse Polish Notation
https://youtu.be/iu0082c4HDE?si=iSLrPASvJdT_CGH-
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for c in tokens:
if c == "+":
a, b = stack.pop(), stack.pop()
stack.append(a + b)
elif c == "-":
a, b = stack.pop(), stack.pop()
stack.append(b - a) # 빼는 순서 중요!!
elif c == "*":
a, b = stack.pop(), stack.pop()
stack.append(a * b)
elif c == "/":
a, b = stack.pop(), stack.pop()
stack.append(int(b / a)) # 나누는 순서 중요!!
else:
stack.append(int(c))
#print(stack)
return stack[0]
'LeetCode > Top Interview 150' 카테고리의 다른 글
List(싸이클탐지): 141. Linked List Cycle (0) | 2024.12.06 |
---|---|
224. Basic Calculator (0) | 2024.12.06 |
71. Simplify Path (0) | 2024.12.06 |
57. Insert Interval (0) | 2024.12.03 |
128. Longest Consecutive Sequence (0) | 2024.12.03 |