题解 | #逆波兰表达式求值#
逆波兰表达式求值
https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param tokens string字符串一维数组
# @return int整型
#
class Solution:
def evalRPN(self , tokens: List[str]) -> int:
# write code here
# 思路:后缀表达式遇到数字就入栈,遇到运算符就取出栈中的两个数字来运算,运算后的结果再入栈,等待与下一个数字运算。
# 先建立辅助栈
num = []
# 遍历输入的表达式
for i,val in enumerate(tokens):
# 数字就入栈
if (val != '+' and val != '-' and val != '*' and val != '/'):
num.append(val)
# 运算符就出栈并运算,运算结果再入栈
elif val == '+':
new_num = int(num.pop(-2)) + int(num.pop(-1))
num.append(new_num)
elif val == '-':
new_num = int(num.pop(-2)) - int(num.pop(-1))
num.append(new_num)
elif val == '*':
new_num = int(num.pop(-2)) * int(num.pop(-1))
num.append(new_num)
elif val == '/':
new_num = int(num.pop(-2)) / int(num.pop(-1))
num.append(new_num)
# 返回值也要记得int强转!!!不然会返回null
return int(num[-1])
#算法笔记#