Faaez Razeen

Evaluate Reverse Polish Notation

  • 1 min read
  • Stacks
  • LC-Medium

3 years ago

Solution

TimeSpaceExplanation
O(n)O(n)
def evalRPN(self, tokens: List[str]) -> int: stack = [] ops = { '+': lambda x, y: x + y, '-': lambda x, y: y - x, '/': lambda x, y: int(y / x), '*': lambda x, y: x * y } for token in tokens: if token in ops: op1, op2 = stack.pop(), stack.pop() stack.append(ops[token](op1, op2)) else: stack.append(int(token)) return stack.pop()