问题
计算逆波兰表示的算术表达式的值。有效的操作符是+,-,*,/。每个操作数可以是一个整数或另一个表达式。
例子:
[“2”, “1”, “+”, “3”, “*”] -> ((2 + 1) * 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6
解决方案
1. 简单方法
这个问题很简单。理解了这个问题之后,我们应该很快意识到这个问题可以通过使用堆栈来解决。我们可以遍历给定数组中的每个元素。当它是一个数字时,将其推入堆栈。当它是一个运算符时,从堆栈中弹出两个数字,进行计算,然后将结果推回去。
下面是代码。通过一个小测试,它运行得很好。但是在leetcode中报编译错误,这是为什么?
public class EvaluateReversePolishNotation {
public static void main(String[] args) throws IOException {
String[] tokens = new String[]{"2", "1", "+", "3", "*"};
System.out.println(evalRPN(tokens));
}
public static int evalRPN(String[] tokens) {
int returnValue = 0;
String operators = "+-*/";
Stack<String> stack = new Stack<String>();
for (String t : tokens) {
if (!operators.contains(t)) {
// 不是运算符就压入栈
stack.push(t);
} else {
// 是运算符就用栈顶2个数字来做运算
Integer a = Integer.valueOf(stack.pop());
Integer b = Integer.valueOf(stack.pop());
switch (t) {
case "+":
stack.push(String.valueOf(a + b));
break;
case "-":
stack.push(String.valueOf(b - a));
break;
case "*":
stack.push(String.valueOf(a * b));
break;
case "/":
stack.push(String.valueOf(b / a));
break;
}
}
}
returnValue = Integer.valueOf(stack.pop());
return returnValue;
}
}
问题是switch字符串语句只在JDK 1.7中可用。Leetcode显然使用的是该版本以下的版本。
2. 可被接受的方法
如果你想使用switch语句,你可以使用下面的代码来转换上面的代码,它使用字符串“±*/”的索引。
public int evalRPN2(String[] tokens) {
int returnValue = 0;
String operators = "+-*/";
Stack<String> stack = new Stack<String>();
for(String t : tokens){
if(!operators.contains(t)){
stack.push(t);
}else{
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
// 使用运算符索引做switch
int index = operators.indexOf(t);
switch(index){
case 0:
stack.push(String.valueOf(a+b));
break;
case 1:
stack.push(String.valueOf(b-a));
break;
case 2:
stack.push(String.valueOf(a*b));
break;
case 3:
stack.push(String.valueOf(b/a));
break; } } }
returnValue = Integer.valueOf(stack.pop());
return returnValue;
}