KK's blog

每天积累多一些

0%

LeetCode 150 Evaluate Reverse Polish Notation

LeetCode



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.

Example 1:

Input: tokens = [“2”,”1”,”+”,”3”,”“]
Output: 9
Explanation: ((2 + 1)
3) = 9


Example 2:

Input: tokens = [“4”,”13”,”5”,”/“,”+”]
Output: 6
Explanation: (4 + (13 / 5)) = 6


Example 3:

Input: tokens = [“10”,”6”,”9”,”3”,”+”,”-11”,”“,”/“,”“,”17”,”+”,”5”,”+”]
Output: 22
Explanation: ((10 (6 / ((9 + 3) -11))) + 17) + 5
= ((10 (6 / (12 -11))) + 17) + 5
= ((10 (6 / -132)) + 17) + 5
= ((10
0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22


Constraints:

1 <= tokens.length <= 10<sup>4</sup> tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].

题目大意:

求逆波兰式计算结果

解题思路:

逆波兰式用Stack

解题步骤:

N/A

注意事项:

  1. 左右操作数是有区别的,所以stack先出栈的为右操作数,后出栈的为左操作数
  2. 最容易错的是向下取整, 题目返回要求整数。所以要除法后取整int(prev / num)。这点和LeetCode 227 Basic Calculator II一样。也是和Java一致,用类型转化来实现,而//是比它小的整数如-2.8就是-3,只在负数是有区别

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token in '+-*/':
operand_right = stack.pop() # remember
operand_left = stack.pop()
if token == '+':
stack.append(operand_left + operand_right)
elif token == '-':
stack.append(operand_left - operand_right)
elif token == '*':
stack.append(operand_left * operand_right)
else:
stack.append(int(operand_left / operand_right)) # remember
else:
stack.append(int(token))
return stack[-1]

算法分析:

时间复杂度为O(n),空间复杂度O(n)

Free mock interview