题解 | #把数字翻译成字符串#
把数字翻译成字符串
http://www.nowcoder.com/practice/046a55e6cd274cffb88fc32dba695668
递归
public int solve (String nums) {
// write code here
return process(nums, 0);
}
public int process(String nums, int index) {
if (index == nums.length()) {
return 1;
}
if (nums.charAt(index) == '0') return 0;
if (index + 1 == nums.length() || ((nums.charAt(index) - '0') * 10 + nums.charAt(index + 1) - '0') > 26) {
return process(nums, index + 1);
}
return process(nums, index + 1) + process(nums, index + 2);
}
动态规划
public int solve (String nums) {
// write code here
char[] str = nums.toCharArray();
int N = str.length;
int[] dp = new int[N];
dp[0] = 1;
for (int i = 1; i < N; i++) {
if (str[i] != '0') {
dp[i] = dp[i - 1];
}
int num = (str[i - 1] - '0') * 10 + str[i] - '0';
if (num >= 10 && num <= 26) {
dp[i] += i == 1 ? 1 : dp[i - 2];
}
}
return dp[N - 1];
}