A message containing letters from A-Z
is being encoded to numbers using the following mapping:
'A' -> 1 'B' -> 2 ... 'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12"
, it could be decoded as "AB"
(1 2) or "L"
(12).
The number of ways decoding "12"
is 2.
Subscribe to see which companies asked this question
动态规划,一个数一个数来,如果当前的数是0,那么d(n)=d(n-2),同时d(n-1)=0(因为不允许0独自存在);如果当前数和之前数不能组成小于26的数,d(n)=d(n-1);其他情况下d(n)=d(n-1)+d(n-2)
public class Solution {
private int calc(String s){
if(s.length()==0)return 1;
if(s.charAt(0)=='0')return 0;
int [] list = new int [s.length()];
list[0]=1;
for(int i=1;i<s.length();i++){
char tem = s.charAt(i);
String temS = ""+s.charAt(i-1)+tem;
if(tem=='0'){
list[i-1]=0;
if(i==1){
list[1]=1;
}else{
list[i]=list[i-2];
}
return list[i];
}else{
if(Integer.parseInt(temS)<=26){
if(i==1)list[i]=list[i-1]+1;
else list[i]=list[i-1]+list[i-2];
}else{
list[i]=list[i-1];
}
}
}
return list[s.length()-1];
}
public int numDecodings(String s) {
if(s.length()==0)return 0;
if(s.charAt(0)=='0')return 0;
int ret = 1;
String tem = "";
for(int i = 0;i<s.length();i++){
if(s.charAt(i)>='1'&&s.charAt(i)<='2'){
tem+=s.charAt(i);
continue;
}else{
tem+=s.charAt(i);
int t = calc(tem);
tem = "";
ret*=t;
}
}
int t = calc(tem);
ret*=t;
return ret;
}
}