根据逆波兰表示法,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
输入: [“2”, “1”, “+”, “3”, “*”]
输出: 9
解释: ((2 + 1) * 3) = 9
示例 2:
输入: [“4”, “13”, “5”, “/”, “+”]
输出: 6
解释: (4 + (13 / 5)) = 6
示例 3:
输入: [“10”, “6”, “9”, “3”, “+”, “-11”, “", “/”, "”, “17”, “+”, “5”, “+”]
输出: 22
解释:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
思路
每个运算符号表示其位置的前两个数字通过该符号进行运算
[“2”, “1”, “+”]
表示‘2+1’
对于每个这样的连续三元素, 计算其结果,并用结果替换这三个元素
[“10”, “6”, “9”, “3”, “+”, “-11”, " * ", “/”, " * ", “17”, “+”, “5”, “+”]的变化过程
[“10”, “6”, (“9”, “3”, “+”), “-11”, " * ", “/”, " * ", “17”, “+”, “5”, “+”] 9+3=12
[“10”, “6”, (“12“, “-11”, " * "), “/”, " * ", “17”, “+”, “5”, “+”] 12*-11=-132
[ " 10 ", ( “6”, “-132”," / " ), " * ", “17”, “+”, “5”, “+”] 6/-132=0
[ (“10”, “0”, " * "), “17”, “+”, “5”, “+”] 10*0=0
[ (“0”, “17”, “+”), “5”, “+”] 0+17=17
["(17", “5”, “+”)] 17+5=22
[22]
用栈会方便很多,将每个元素入栈,当栈顶元素为运算符号时,将栈顶三个元素替换为其计算结果
代码
第一名的代码
def evalRPN(self, tokens):
stack=[]
for i in tokens:
if i!='+' and i!='-' and i!='*' and i!='/':
stack.append(int(i))
else:
a=stack.pop()
b=stack.pop()
if i=='+':
stack.append(a+b)
elif i=='-':
stack.append(b-a)
elif i=='*':
stack.append(a*b)
elif i=='/':
if a*b<0:
stack.append(-((-b)//a))
else:
stack.append(b//a)
return stack.pop()