http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
Solution in Python:
class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
#from collections import deque
q = collections.deque()
for val in tokens:
if val not in ['+', '-', '*', '/']:
q.append(val)
else:
op1 = int(q.pop())
op2 = int(q.pop())
if val == '-':
result = op2 - op1
elif val == '+':
result = op2 + op1
elif val == '*':
result = op1*op2
elif val == '/':
result = int(op2/float(op1))
q.append(result)
return int(q.pop())
这道比较简单的题目使用了一个stack。在python中list可以很方便地实现stack所以解法里面可以不import collections