Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won’t be any divide by zero operation.
Example 1:
Input: [“2”, “1”, “+”, “3”, “*”]
Output: 9
Explanation: ((2 + 1) * 3) = 9
将给定的String数组中的数字符号用逆波兰法计算出值
思路:
逆波兰法:逆波兰记法中,操作符置于操作数的后面。例如表达“三加四”时,写作“3 4 +”,而不是“3 + 4”。如果有多个操作符,操作符置于第二个操作数的后面,所以常规中缀记法的“3 - 4 + 5”在逆波兰记法中写作“3 4 - 5 +”:先3减去4,再加上5。使用逆波兰记法的一个好处是不需要使用括号。例如中缀记法中“3 - 4 * 5”与“(3 - 4)*5”不相同,但后缀记法中前者写做“3 4 5 * -”,无歧义地表示“3 (4 5 *) -”;后者写做“3 4 - 5 *”
逆波兰表达式的解释器一般是基于堆栈的。解释过程一般是:操作数入栈;遇到操作符时,操作数出栈,求值,将结果入栈;当一遍后,栈顶就是表达式的值。
需要注意的是,在减法和除法的时候,注意被减数和减数的顺序
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
if (isOperator(tokens[i])) {
int a = stack.pop();
int b = stack.pop();
switch(tokens[i]) {
case "+":
stack.push(a + b);
break;
case "-":
stack.push(b - a);
break;
case "*":
stack.push(a * b);
break;
case "/":
stack.push(b / a);
break;
}
} else {
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
public boolean isOperator(String op) {
if (op.equals("+") || op.equals("-") || op.equals("*") || op.equals("/")) {
return true;
}
return false;
}