【题目】给定一个字符串str,str全部由数组字符组成,如果str中某一个或某相邻两个字符组成的子串值在1~26之间,则这个子串可以转换为一个字母。规定“1”转换为“A",“2"转换为”B”,“3"转换为“C”…“26转换为”Z”.写一个函数,求str有多少种不同的转换结果,并返回种数。
public class NumToStr {
// 暴力递归
public static int num1(String str) {
if (str == null || str.equals("")) {
return 0;
}
char[] chas = str.toCharArray();
return process(chas, 0);
}
public static int process(char[] chas, int i) {
if (i == chas.length) {
return 1;
}
if (chas[i] == '0') {
return 0;
}
int res = process(chas, i + 1);
if (i + 1 < chas.length && (chas[i] - '0') * 10 + chas[i + 1] - '0' < 27) {
res += process(chas, i + 2);
}
return res;
}
// dp
public static int num2(String str) {
if (str == null || str.equals("")) {
return 0;
}
char[] chas = str.toCharArray();
int next = 1;
int cur = chas[chas.length - 1] == '0' ? 0 : 1;
int tmp = 0;
for (int i = chas.length - 2; i >= 0; i--) {
if (chas[i] == '0') {
next = cur;
cur = 0;
} else {
tmp = cur;
if ((chas[i] - '0') * 10 + chas[i + 1] - '0' < 27) {
cur += next;
}
cur = tmp;
}
}
return cur;
}
}