LeetCode 150. Evaluate Reverse Polish Notation
考点 | 难度 |
---|---|
Math | Medium |
题目
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, and /. Each operand may be an integer or another expression.
Note that division between two integers should truncate toward zero.
It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.
思路
用stack储存数字,每次遇到符号就pop两个数字,和valid parenthesis 很像
答案
class Solution(object):
def evalRPN(self, tokens):
stack = []
for t in tokens:
if t not in "+-*/":
stack.append(int(t))
else:
r, l = stack.pop(), stack.pop()
if t == "+":
stack.append(l+r)
elif t == "-":
stack.append(l-r)
elif t == "*":
stack.append(l*r)
else:
stack.append(int(float(l)/r))
return stack.pop()