Skip to content

Latest commit

 

History

History
36 lines (28 loc) · 1.31 KB

150.-evaluate-reverse-polish-notation.md

File metadata and controls

36 lines (28 loc) · 1.31 KB

150. Evaluate Reverse Polish Notation

  • 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.

Analyze

Accroding to the given definition, the RPN is different in that the "+-*/" symbols come after the numbers. Therefore a stack would come into great use in this scenario.

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()