Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
翻译就是 用后缀表达式评估表达式的值
这就很明显了,要用栈Stack
入栈方法是push();
出栈方法是pop();
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)) {// 方法返回true,当且仅当此字符串包含指定的char值序列即operator在t里
stack.push(t);
} else {
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
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;
}
解释一下就是
例如 String[] s = { "2", "1", "+", "3", "*" };
把+-*/符号声明为一个数组operator,传入的表达式数组为tokens;
遍历tokens,把不是符号的内容入栈,也就是2 1;
然后到了是符号的 +;
先出栈,a=1;b=2;
index是+号在之前定义是数组operator中的第一个,下标是0;
0在catch里找到对应计算是相加,也就是1+2,结果是3,把3再入栈;
****
再回到开始;
遍历目前的栈,把不是符号的内容入栈,也就是3 3,第一个3是之前算1+2=3的那个3;
然后到了是符号的 *;
出栈,a=3,b=3;
*在catch里对应计算3*3=9,9入栈;
循环完毕,把结果出栈,就是最后我们要求的后缀表达式的结果。