150. Evaluate Reverse Polish Notation

https://leetcode.com/problems/evaluate-reverse-polish-notation/

solution

  • 注意运算顺序与栈的顺序

  • python中如何将字符串符号对应为运算符

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        # op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)}

        for token in tokens:
            if token in ['+', '-', '*', '/']:
                a = stack.pop(-1)
                b = stack.pop(-1)
                if token == '+':
                    x = a + b
                elif token == '-':
                    x = b - a
                elif token == '*':
                    x = b * a
                elif token == '/':
                    x = b / a    
                else:
                    raise ValueError
                
                stack.append(int(x))
            else:
                stack.append(int(token))
        return stack[-1]

时间复杂度:O(n) 空间复杂度:O(n)

Last updated