[LeetCode] Evaluate Reverse Polish Notation (Python)
2024. 3. 6. 14:10ㆍ자료구조
import math
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
operation = ["+", "-", "*", "/"]
stack = []
if len(tokens) == 1:
return int(tokens[0])
for i in range(len(tokens)):
if tokens[i] not in operation:
stack.append(int(tokens[i]))
else:
num1 = stack.pop()
num2 = stack.pop()
new_num = 0
if tokens[i] == "+":
new_num = num2 + num1
elif tokens[i] == "-":
new_num = num2 - num1
elif tokens[i] == "*":
new_num = num2 * num1
else:
new_num = num2 / num1
new_num = math.trunc(new_num)
stack.append(new_num)
return stack.pop()
'자료구조' 카테고리의 다른 글
[LeetCode] Kth Largest Element in an Array (Python) (0) | 2024.03.12 |
---|---|
[LeetCode] Sort Colors (Python) (0) | 2024.03.12 |
[LeetCode] Min Stack (Python) (0) | 2024.03.06 |
[LeetCode] Design Circular Queue (Python) (0) | 2024.03.05 |
[LeetCode] Find All Numbers Disappeared in an Array (Python) (0) | 2024.03.03 |