public class Code4_ConvertToLetterString {
public static int ToString(String str) {
char[] str_temp = str.toCharArray();
return process(str_temp, 0);
}
public static int process(char[] str, int index) {
if (index == str.length) {
return 1;
}
if (str[index] == '0') {
return 0;
}
int ways = process(str, index + 1);// 单个数字字符转
if (index + 1 < str.length && ((str[index] - '0') * 10 + str[index + 1] - '0') < 27) {// 连续两个数字字符一起转
ways += process(str, index + 2);
}
return ways;
}
public static int dp(String s) {
char[] str = s.toCharArray();
int[] dp = new int[str.length + 1];
dp[str.length] = 1;
for (int index = str.length - 1; index >= 0; index--) {
if (str[index] != '0') {
int ways = dp[index + 1];
if (index + 1 < str.length && ((str[index] - '0') * 10 + str[index + 1] - '0') < 27) {// 连续两个数字字符一起转
ways += dp[index + 2];
}
dp[index] = ways;
}
}
return dp[0];
}
public static void main(String[] args) {
String str = "7210231231232031203123";
System.out.println(ToString(str));
System.out.println(dp(str));
}
}
每日一题动态规划-2 【从暴力递归到动态规划:两种解法】
最新推荐文章于 2024-11-02 13:05:10 发布