1、逆波兰式
逆波兰式(Reverse Polish Notation,RPN,或逆波兰记法),也叫后缀表达式(将运算符写在操作数之后)
2、思想
(1)如果E是一个变量或常量,则E的后缀式是E本身。
(2)如果E是E1 op E2形式的表达式,这里op是任何二元操作符,则E的后缀式为E1’E2’ op,这里E1’和E2’分别为E1和E2的后缀式。
(3)如果E是(E1)形式的表达式,则E1的后缀式就是E的后缀式。
3、问题实现
描述
给定一个逆波兰表达式,求表达式的值。
数据范围:表达式长度满足1≤n≤10000,表达式中仅包含数字和 + ,- , * , / ,其中数字的大小满足∣val∣≤200 。
public int evalRPN (String[] tokens) {
//创建辅助栈,用来存储数字
Stack<Integer> number = new Stack<>();
//遍历字符串一维数组
for (int i = 0; i < tokens.length; i++) {
//简化代码,用c替代tokens[i]
String c = tokens[i];
//判断该字符串是否为+
if (c.equals("+")) {
//弹出两次栈顶
int a = number.pop();
int b = number.pop();
//将弹出的数字相加后压入栈中
number.push(a + b);
//判断该字符串是否为-
} else if (c.equals("-")) {
//弹出两次栈顶
int a = number.pop();
int b = number.pop();
//将弹出的数字相减后压入栈中
number.push(b - a);
//判断该字符串是否为*
} else if (c.equals("*")) {
//弹出两次栈顶
int a = number.pop();
int b = number.pop();
//将弹出的数字相乘后压入栈中
number.push(a * b);
}
//判断该字符串是否为/
else if (c.equals("/")) {
//弹出两次栈顶
int a = number.pop();
int b = number.pop();
//将弹出的数字相除后压入栈中
number.push(b / a);
//如果都不是加减乘除,那么就只能是数字了,所以将其加入数字栈中
} else {
number.push(Integer.parseInt(c));
}
}
//返回栈中最后一个数
return number.peek();
}
这个问题主要是简单的逆波兰式,没有涉及优先级!!!