leetcode 150. Evaluate Reverse Polish Notation

题目链接

思路:逆波兰用栈来做

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for token in tokens:
if token in '+-*/':
num2 = stack.pop()
num1 = stack.pop()
if token == '+':
num = int(num1)+int(num2)
stack.append(str(num))
elif token == '-':
num = int(num1)-int(num2)
stack.append(str(num))
elif token == '*':
num = int(num1)*int(num2)
stack.append(str(num))
else:
num = int(int(num1)/int(num2))
stack.append(str(num))
else:
stack.append(token)
return int(stack[0])