Reverse Polish Expression Evaluation
Topic description: Find the value of an expression according to Reverse Polish notation.
Valid operators include +, -, *, /. Each operand can be an integer or another Reverse Polish expression.
Description:
- Integer division preserves only the integer part.
- The given Reverse Polish expression is always valid. In other words, the expression always yields a valid number and there is no division by zero.
Reverse Polish Expression: details, see Reverse Polish Expression
For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: Stack
The value of the reverse Polish expression (suffix expression) is solved by using the last-in-first-out feature of the stack. The specific solution process is as follows:
- If the original expression has only one parameter, the operand is returned directly.
Otherwise, declare an operand stack nums to hold the operands, traversing the characters of the reverse Polish expression in order:
- If the current character is an operand, it is directly pushed onto the stack;
- If the current character is an operator, 2 operands are taken from the stack, and the calculation is performed according to the current operator, and the calculation result is recalculated.
- Finally, return the only value of the operand stack, which is the result of evaluating the reverse Polish expression.
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class LeetCode_150 {
public static int evalRPN(String[] tokens) {
if (tokens.length == 1) {
return Integer.valueOf(tokens[0]);
}
List<String> operatorList = new ArrayList<>();
operatorList.add("+");
operatorList.add("-");
operatorList.add("*");
operatorList.add("/");
// 操作数栈
Stack<Integer> nums = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
if (operatorList.contains(tokens[i])) {
// 如果是操作符,取出2个操作数进行运算然后将结果重新入栈
int num1 = Integer.valueOf(nums.pop());
int num2 = Integer.valueOf(nums.pop());
if ("+".equals(tokens[i])) {
nums.push(num2 + num1);
} else if ("-".equals(tokens[i])) {
nums.push(num2 - num1);
} else if ("*".equals(tokens[i])) {
nums.push(num2 * num1);
} else if ("/".equals(tokens[i])) {
nums.push(num2 / num1);
}
} else {
// 如果是操作数,则入栈
nums.push(Integer.valueOf(tokens[i]));
}
}
return nums.pop();
}
public static void main(String[] args) {
// 测试用例
String[] tokens = new String[]{"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
// 转换成中缀表达式的结果是: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
// 计算结果为: 22
System.out.println(evalRPN(tokens));
}
}
[Daily Message] There is nothing difficult in the world, as long as you are willing to climb.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。