首页 > 代码库 > 【leetcode】Evaluate Reverse Polish Notation

【leetcode】Evaluate Reverse Polish Notation

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)

 1 class Solution: 2     # @param tokens, a list of string 3     # @return an integer 4     def evalRPN(self, tokens): 5         ops = [+,-,*,/] 6         l = len(tokens) 7         op = [] 8         for i in range(l): 9             if tokens[i] == +:10                 t = op[-1] + op[-2]11                 op.pop()12                 op.pop()13                 op.append(t)14             elif tokens[i] == -:15                 t = op[-2] - op[-1]16                 op.pop()17                 op.pop()18                 op.append(t)19             elif tokens[i] == *:20                 t = op[-1] * op[-2]21                 op.pop()22                 op.pop()23                 op.append(t)24             elif tokens[i] == /:25                 t = int(op[-2]*1.0 / op[-1]*1.0)26                 op.pop()27                 op.pop()28                 op.append(t)29             else:30                 op.append(int(tokens[i]))31         return op[-1]32         33 def main():34     s = Solution()35     print s.evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"])36     37 if __name__ == __main__:38     main()

 

【leetcode】Evaluate Reverse Polish Notation