LeetCode 150. 逆波兰表达式求值
题目描述
思路分析
我们可以使用栈来解决这个问题。遍历逆波兰表达式中的每一个元素:
- 如果是数字,则将其压入栈中。
- 如果是运算符,则从栈中弹出两个数字,进行相应的运算,然后将结果压回栈中。
- 最后栈中只会剩下一个元素,即为表达式的结果。
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
func evalRPN(tokens []string) int {
var stack []int
calc := func(op string, b, a int) int {
switch op {
case "+":
return a + b
case "-":
return a - b
case "*":
return a * b
case "/":
return a / b
}
return 0
}
for _, token := range tokens {
switch token {
case "+", "-", "*", "/":
b := stack[len(stack)-1]
stack = stack[:len(stack)-1]
a := stack[len(stack)-1]
stack = stack[:len(stack)-1]
stack = append(stack, calc(token, b, a))
default:
num, _ := strconv.Atoi(token)
stack = append(stack, num)
}
}
return stack[0]
}
- 时间复杂度:O(n),其中 n 是 token 的个数,每个 token 只被访问一次。
- 空间复杂度:O(n),使用了栈结构,最坏情况下所有元素都是数字都要压入栈中。
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用