Java Reverse Polish Expression
A normal expression is called an infix expression. The operator is in the middle, which is mainly for human reading, and it is not convenient for machines to solve it.
Example: 3 + 5 * (2 + 6) - 1
Also, parentheses are often required to change the order of operations.
Conversely, if the reverse Polish expression (prefix expression) is used, the above expression is expressed as:
-
- 3 * 5 + 2 6 1
Parentheses are no longer needed, and the machine can easily solve it recursively.
For simplicity, we assume:
- There are only + - * three operators
- Each operand is a non-negative integer less than 10
The following program evaluates a reverse Polish representation string.
Its return value is an array: the first element is the result of the evaluation, and the second is the number of characters it has parsed.
static int[] evaluate(String x) { if (x.length() == 0) return new int[] { 0, 0 };
char c = x.charAt(0);
if (c >= '0' && c <= '9')
return new int[] { c - '0', 1 };
int[] v1 = evaluate(x.substring(1));
int[] v2 = __________________________________________; // 填空位置
int v = Integer.MAX_VALUE;
if (c == '+')
v = v1[0] + v2[0];
if (c == '*')
v = v1[0] * v2[0];
if (c == '-')
v = v1[0] - v2[0];
return new int[] { v, 1 + v1[1] + v2[1] };
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int t[] = evaluate("-+3*5+261");
System.out.println(t[0]);
}
static int[] evaluate(String x) {
// 3 * 5 + 2 6 1
// + 3 * 5 + 2 6 1
// - + 3 * 5 + 2 6 1
if (x.length() == 0)
return new int[] {
0, 0 };
char c = x.charAt(0);
if (c >= '0' && c <= '9')
return new int[] {
c - '0', 1 };
int[] v1 = evaluate(x.substring(1));
// [3][1]
int[] v2 = evaluate(x.substring(v1[1] + 1)); // 填空位置
int v = Integer.MAX_VALUE;
if (c == '+')
v = v1[0] + v2[0];
if (c == '*')
v = v1[0] * v2[0];
if (c == '-')
v = v1[0] - v2[0];
return new int[] {
v, 1 + v1[1] + v2[1] };
}
Fill in the blanks: evaluate(x.substring(v1[1] + 1));