题解 | #把数字翻译成字符串#
把数字翻译成字符串
http://www.nowcoder.com/practice/046a55e6cd274cffb88fc32dba695668
import java.util.*;
public class Solution {
/**
* 解码
* @param nums string字符串 数字串
* @return int整型
*/
public int solve (String nums) {
// write code here
char[] ch = nums.toCharArray();
int n = ch.length;
int[] dp = new int[n+1];
dp[n] = 1;
for(int i = n-1;i>=0;i--){
if(ch[i] == '0'){
dp[i] = 0;
}else if(ch[i] == '1'){
int ans = dp[i+1];
if(i+1<ch.length){
ans += dp[i+2];
}
dp[i] = ans;
}else if(ch[i] == '2'){
int ans = dp[i+1];
if(i+1<ch.length&&ch[i+1]<'7'){
ans += dp[i+2];
}
dp[i] = ans;
}else{
dp[i] = dp[i+1];
}
}
return dp[0];
}
}
public class Solution {
/**
* 解码
* @param nums string字符串 数字串
* @return int整型
*/
public int solve (String nums) {
// write code here
char[] ch = nums.toCharArray();
int n = ch.length;
int[] dp = new int[n+1];
dp[n] = 1;
for(int i = n-1;i>=0;i--){
if(ch[i] == '0'){
dp[i] = 0;
}else if(ch[i] == '1'){
int ans = dp[i+1];
if(i+1<ch.length){
ans += dp[i+2];
}
dp[i] = ans;
}else if(ch[i] == '2'){
int ans = dp[i+1];
if(i+1<ch.length&&ch[i+1]<'7'){
ans += dp[i+2];
}
dp[i] = ans;
}else{
dp[i] = dp[i+1];
}
}
return dp[0];
}
}