150.逆波兰表达式求值

1
2
3
4
5
6
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,
也可以是另一个逆波兰表达式。

说明:
整数除法只保留整数部分。给定逆波兰表达式总是有效的。
换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
示例 1:

输入:["2", "1", "+", "3", "*"]
输出: 9
解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
示例 2:

输入:["4", "13", "5", "/", "+"]
输出: 6
解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
示例 3:

输入:["10","6","9","3","+","-11","*","/","*", "17", "+", "5", "+"]
输出: 22
解释:
该算式转化为常见的中缀算术表达式为:
((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

中缀表达式 后缀表达式
1+2 1 2 +
2 + 3 * 4 2 3 4 * +
9 + (4 - 1) * 2 9 4 1 - 2 * +

使用栈(非最优解)

  • 用stack栈依次push数值
  • 遇到符号pop两个进行计算
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
public static int evalRPN(String[] tokens) {
Stack<Integer> numStack = new Stack<>();
Integer op1, op2;
for (String s : tokens) {
switch (s) {
case "+":
op2 = numStack.pop();
op1 = numStack.pop();
numStack.push(op1 + op2);
break;
case "-":
op2 = numStack.pop();
op1 = numStack.pop();
numStack.push(op1 - op2);
break;
case "*":
op2 = numStack.pop();
op1 = numStack.pop();
numStack.push(op1 * op2);
break;
case "/":
op2 = numStack.pop();
op1 = numStack.pop();
numStack.push(op1 / op2);
break;
default:
numStack.push(Integer.valueOf(s));
break;
}
}
return numStack.pop();
}

数组模拟栈

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
public static int evalRPN(String[] tokens) {
int[] numStack = new int[tokens.length / 2 + 1];
int index = 0;
for (String s : tokens) {
switch (s) {
case "+":
numStack[index - 2] += numStack[--index];
break;
case "-":
numStack[index - 2] -= numStack[--index];
break;
case "*":
numStack[index - 2] *= numStack[--index];
break;
case "/":
numStack[index - 2] /= numStack[--index];
break;
default:
// numStack[index++] = Integer.valueOf(s);
//valueOf改为parseInt,减少自动拆箱装箱操作
numStack[index++] = Integer.parseInt(s);
break;
}
}
return numStack[0];
}
作者

黄港欢

发布于

2020-06-16

更新于

2021-04-08

许可协议