题目:
题解:
- class Solution:
- def evalRPN(self, tokens: List[str]) -> int:
- op_to_binary_fn = {
- "+": add,
- "-": sub,
- "*": mul,
- "/": lambda x, y: int(x / y), # 需要注意 python 中负数除法的表现与题目不一致
- }
-
- n = len(tokens)
- stack = [0] * ((n + 1) // 2)
- index = -1
- for token in tokens:
- try:
- num = int(token)
- index += 1
- stack[index] = num
- except ValueError:
- index -= 1
- stack[index] = op_to_binary_fn[token](stack[index], stack[index + 1])
-
- return stack[0]