题目 逆波兰表达式
方法一
首先大致浏览代码, 整体把握, v2
是要和 v1
进行运算的, 不要对 v1
的递归进行解读, 获取的第一个字符是 -
号, 那么v2
一定是获取 数字1
的, 也就是 v1
没有解析到的部分.
遇到这种题要大胆猜想, 再用题目给的数据进行验证.
import java.util.*;
public class Main {
static int[] evaluate(String x) {
if (x.length() == 0)
return new int[] { 0, 0 }; // 如果字符串长度为0 直接返回
char c = x.charAt(0); // 获取第一个字符
if (c >= '0' && c <= '9') // 这个字符是0-9 的话
return new int[] { c - '0', 1 };
int[] v1 = evaluate(x.substring(1)); // 第一个字符是运算符, 截取后面的部分
int[] v2 = evaluate(x.substring(1 + v1[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] };
}
public static void main(String[] args) {
System.out.println(evaluate("-+3*5+261")[0]);
System.out.println(evaluate("+*35*42")[0]);
}
}