当前位置:   article > 正文

Leetcode 150. Evaluate Reverse Polish Notation

Leetcode 150. Evaluate Reverse Polish Notation

Problem

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.

Algorithm

Recursion. From the right to left to calculate the expression.

Code

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        
        slen = len(tokens)
        def dfs(R):
            if tokens[R] == "+" or tokens[R] == "-" or tokens[R] == "*" or tokens[R] == "/":
                Rv = dfs(R-1)
                Lv = dfs(Rv[0])
            if tokens[R] == "+":
                return [Lv[0], Lv[1]+Rv[1]]
            elif tokens[R] == "-":
                return [Lv[0], Lv[1]-Rv[1]]
            elif tokens[R] == "*":
                return [Lv[0], Lv[1]*Rv[1]]
            elif tokens[R] == "/":
                if abs(Lv[1]) < abs(Rv[1]):
                    return [Lv[0], 0]
                else:
                    return [Lv[0], int(Lv[1]/Rv[1])]
            else:
                return [R-1, int(tokens[R])]
            
        ans = dfs(slen-1)
        return ans[1]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/493444
推荐阅读
相关标签
  

闽ICP备14008679号