题目:根据 逆波兰表示法,求该后缀表达式的计算结果。
有效的算符包括 +、-、*、/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
从左到右扫描数组,遇到操作数则入栈,遇到操作符则取出栈顶元素和第二个元素进行运算,运算完的的结果重新入栈直到遇到下一个操作符。
public static int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < tokens.length; ++i){
if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/"){
int sum = Integer.valueOf(tokens[i]);
stack.push(sum);
}else{
int a = stack.pop();
int b = stack.pop();
if (tokens[i] == "+"){
int c = add(a, b);
stack.push(c);
}else if (tokens[i] == "-"){
int c = jian(a, b);
stack.push(c);
}else if (tokens[i] == "*"){
int c = cheng(a, b);
stack.push(c);
}else if (tokens[i] == "/"){
int c = chu(a, b);
stack.push(c);
}
}
}
return stack.pop();
}
public static int add(int a, int b){
return a + b;
}
public static int jian(int a, int b){
return a - b;
}
public static int cheng(int a, int b){
return a * b;
}
public static int chu(int a, int b){
return a / b;
}
优化后的:
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String c : tokens) {
switch (c) {
case "+":
case "-":
case "*":
case "/":
int num2 = stack.pop();
int num1 = stack.pop();
stack.push(calc(num1, num2, c));
break;
default:
stack.push(Integer.parseInt(c));
}
}
return stack.pop();
}
private int calc(int a, int b, String op) {
switch (op) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
default:
return a / b;
}
}