Evaluate Reverse Polish Notation
题目描述:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, , /. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", ""] -> ((2 + 1) 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
*简单的来说就是计算逆波兰式的值。
解题思路:
这就是一个弹栈进栈的问题,根据弹出的元素类型和栈顶的元素的类型不同得出不同的结果。输入里卖弄无非就是数字和运算符这两种情况,组合一下有下面这几种情况:
1.弹出的是数字,下一个还是数字:压栈,等待运算符进行计算
2.弹出的是数字,下一个是运算符:压栈,等待运算符计算
3.弹出的是运算符,下一个是数字:从栈中弹出两个操作数计算
4.弹出的是运算符,下一个是运算符:从栈中取出两个操作数计算
综合一下就是:数字就压栈,运算符就弹出两个数计算
需要注意的:
注意这里除法的取整方式,应该是先计算出浮点数的结果再取整int(op[-2]*1.0 / op[-1]*1.0)
class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
ops = ['+','-','*','/']
l = len(tokens)
op = []
for i in range(l):
if tokens[i] == '+':
t = op[-1] + op[-2]
op.pop()
op.pop()
op.append(t)
elif tokens[i] == '-':
t = op[-2] - op[-1]
op.pop()
op.pop()
op.append(t)
elif tokens[i] == '*':
t = op[-1] * op[-2]
op.pop()
op.pop()
op.append(t)
elif tokens[i] == '/':
t = int(op[-2]*1.0 / op[-1]*1.0)
op.pop()
op.pop()
op.append(t)
else:
op.append(int(tokens[i]))
return op[-1] def main():
s = Solution()
print s.evalRPN(["","","","","+","-11","*","/","*","","+","","+"]) if __name__ == '__main__':
main()