You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
def add (a,b):
return a + b
def subtract (a,b):
return a - b
def multiply (a,b):
return a * b
def divide (a,b):
return int(a / b)
stack = []
oprs = {'+': add,
'-': subtract,
'*': multiply,
'/': divide
}
for op in tokens:
if op not in oprs:
stack.append(int(op))
else:
b = stack.pop()
a = stack.pop()
new = oprs[op](a, b)
stack.append(new)
return stack.pop()
