public class Test55 { //规定1与A对应,2与B对应…… //那么一个数字字符串“111”可转为AAA,KA,AK //给定一个字符串str,返回多少种转化结果 public static int dpWay(String s) { if (s == null || s.length() == 0) { return 0; } char[] str = s.toCharArray(); int N = str.length; int[] dp = new int[N + 1]; dp[N] = 1; for (int i = N - 1; i >= 0; i--) { if (str[i] == '0') { dp[i] = 0; } if (str[i] == '1') { dp[i] = dp[i + 1]; if (i + 1 < str.length) { dp[i] += dp[i + 2]; } } if (str[i] == '2') { dp[i] = dp[i + 1]; if (i + 1 < str.length && (str[i + 1] >= '0' && str[i + 1] <= '6')) { dp[i] += dp[i + 2]; } } } return dp[0]; } }
转换字符串
于 2024-08-22 14:45:48 首次发布