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]

你可能感兴趣的:(Leetcode,leetcode,深度优先,算法)