题解 | #把数字翻译成字符串#
把数字翻译成字符串
http://www.nowcoder.com/practice/046a55e6cd274cffb88fc32dba695668
//1.递归版本
public int solve1 (String nums) {
return process(nums.toCharArray(),0,nums.length());
}
//返回从[idx...len)可能的译码结果
public int process(char[] chars,int idx,int N){
if(idx==N) return 1;
if(chars[idx]=='0') return 0;
int cur = 0;
int res = 0;
while(idx<N&&(cur = cur*10+(chars[idx]-'0'))<=26){
res+=process(chars,++idx,N);
}
return res;
}
//2.递归转动态规划
public int solve (String nums) {
if(nums==null||nums.length()==0) return 0;
int N = nums.length();
int[] dp = new int[N+1];
dp[N] = 1;
for(int i = N-1;i>=0;i--){
if(nums.charAt(i)=='0'){
dp[i] = 0;//需要特别注意的是,以'0'开头是不会有情况的
}else{
int cur = 0;
int res = 0;
int idx = i;
while(idx<N&&(cur = cur*10+(nums.charAt(idx)-'0'))<=26){
res+=dp[++idx];
}
dp[i] = res;
}
}
return dp[0];
}
waigo的刷题之路 文章被收录于专栏
收录平时刷题的题解