150. Inverse Polish expression evaluation
According to the reverse Polish notation, find the value of the expression.
Valid operators include +, -, *, /. Each operand can be an integer or another inverse Polish expression.
Description:
Integer division only keeps the integer part.
The given reverse Polish expression is always valid. In other words, the expression always yields a valid value and there is no case where the divisor is zero.
Example 1:
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: This formula is converted into a common infix arithmetic expression: ((2 + 1) * 3) = 9
Example 2:
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: This formula is converted into a common infix arithmetic expression: (4 + (13 / 5 )) = 6
Example 3:
Input: tokens = ["10","6","9","3","+","-11"," ","/"," ","17","+","5 ","+"]
Output: 22
Explanation:
This formula is converted to a common infix arithmetic expression:
((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
prompt:
1 <= tokens.length <= 104
tokens[i] is either an operator ("+", "-", "*" or "/") or an integer in the range [-200, 200]
Inverse Polish expression:
Inverse Polish expression is a kind of postfix expression. The so-called postfix means that the operator is written behind.
The commonly used formula is an infix expression, such as (1 + 2) * (3 + 4).
The inverse Polish expression of this formula is written as ((1 2 +) (3 4 +) *).
Inverse Polish expressions mainly have the following two advantages:
After removing the parentheses, the expression is unambiguous. Even if the above formula is written as 1 2 + 3 4 + *, the correct result can be calculated according to the order.
It is suitable for stack operation operations: when encountering a number, it is pushed into the stack; when encountering an operator, the two numbers on the top of the stack are taken out for calculation, and the result is pushed into the stack.
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new LinkedList<Integer>();
int num = tokens.length;
for (int i=0; i<num; i++) {
String token = tokens[i];
if (isNumber(token)) {
stack.push(Integer.parseInt(token)); // 字符串转int
} else {
int num2 = stack.pop();
int num1 = stack.pop();
switch (token) {
case "+" : stack.push(num1+num2); break;
case "-" : stack.push(num1-num2); break;
case "*" : stack.push(num1*num2); break;
case "/" : stack.push(num1/num2); break;
default:
}
}
}
return stack.pop();
}
// 判断 从栈中取出的是+-*/ 还是数字
public boolean isNumber(String token) {
return !("+".equals(token) || "-".equals(token) || "*".equals(token) || "/".equals(token));
}