堆栈,时间复杂度O(n),空间复杂度O(n)
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for c in tokens:
if c in ["+", "-", "*", "/"]: # Note(1)
num_after = stack.pop() # Note(2)
num_before = stack.pop()
if c == '+':
res = num_before + num_after
elif c == '-':
res = num_before - num_after
elif c == '/':
res = int(num_before / num_after) # Note(3)
elif c == '*':
res = num_before * num_after
stack.append(res)
else:
# c是数字
stack.append(int(c))
return stack[0]
思路用堆栈,有三个坑和细节,避免大家踩到
Note(1) 数字会大于10,不能用 ‘0’ <= c <= '9’判断是否是数字
Note(2) 堆栈顶先弹出来的是运算符后面的数字num2,后弹出来的是运算符前面的数字num1, 顺序要对啊
Note(3) python的除法和题目描述中的除法不一致,需要int取整
最后的大boss:python只维护到2020年,进化后的python3不向下兼容,之前的题目是在python编译器里边编译的,以后咱们还是用python3的吧~哈哈哈哈