Leetcode原题链接:逆波兰表达式求值
一、思路
- 遍历,遇到数字压入栈,遇到算数符
pop
出两个数字进行运算
二、个人代码
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
operators = ['+', '-', '*', '/']
nums = []
tmp = 0
for i in tokens:
if i not in operators:
tmp = i
nums.append(i)
else:
a = int(nums.pop())
b = int(nums.pop())
if i == '+':
tmp = int(a + b)
nums.append(tmp)
elif i == '-':
tmp = int(b - a)
nums.append(tmp)
elif i == '*':
tmp = int(a * b)
nums.append(tmp)
elif i == '/':
tmp = int(b / a)
nums.append(tmp)
return int(nums.pop())
三、强者代码
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for item in tokens:
if item not in {"+", "-", "*", "/"}:
stack.append(item)
else:
first_num, second_num = stack.pop(), stack.pop()
result = int(eval(f'{second_num} {item} {first_num}'))
stack.append(result)
return int(stack.pop())
四、总结
- 一些个新知识,
eval
方法:接收运行一个字符串表达式(必须是字符串),返回表达式的结果值。 - 同样的内容,放入列表和放入字典相比,在查询时,字典更快。
部分内容参考代码随想录