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. Note that division between two integers should truncate toward zero.
Constraints:
- 1 <= tokens.length <= 10^4
- tokens[i] is either an operator (+, -, *, /), or an integer in the range [-200, 200]
Examples:
Input: ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Solutions
Stack
We use a stack to store the intermediate results. When we encounter an operator, we pop the top two elements from the stack, apply the operation, and push the result back to the stack. When we encounter an operand, we simply push it to the stack.
def evalRPN(tokens):
stack = []
for token in tokens:
if token in {"+", "-", "*", "/"}:
b = stack.pop()
a = stack.pop()
if token == "+":
stack.append(a + b)
if token == "-":
stack.append(a - b)
if token == "*":
stack.append(a * b)
if token == "/":
stack.append(int(a / b))
else:
stack.append(int(token))
return stack[0]
Follow-up:
How would you optimize the solution for very large inputs?