1. Description
Given a string only containing numbers and '*', return the total number of ways to decode it.
'*' can be treated as 1 to 9.
2. Solution
Dynamic Programming.
dp[i] refers to the number of ways to decode the first i elements in the string.
3. Code
int mod = 1000000007;
int numDecodings(string s) {
int n = s.size();
if(n==0)
return 0;
long dp[n+1];
dp[0]=1;
if(s[0]=='0')
dp[1]=0;
else if(s[0]=='*')
dp[1]=9;
else
dp[1]=1;
for(int i=2;i<=n;i++){
dp[i]=0;
if(s[i-1]!='0'){
if(s[i-1]=='*')
dp[i]=((dp[i-1]%mod)*9)%mod;
else
dp[i]=dp[i-1]%mod;
}
if(s[i-2]=='0') continue;
if(s[i-2]>'0'&&s[i-2]<='9'&&s[i-1]>='0'&&s[i-1]<='9'){
string str;
str+= s[i-2];
str+= s[i-1];
int a = atoi(str.c_str());
if(a<=26 && a>0)
dp[i]+=(dp[i-2]%mod);
dp[i]=dp[i]%mod;
continue;
}
if(s[i-2]=='*'&&s[i-1]>='0'&&s[i-1]<='9'){
dp[i]+=(dp[i-2]%mod);//s[i-2]==1
if(s[i-1]>='0'&&s[i-1]<='6')
dp[i]+=(dp[i-2]%mod);//s[i-2]==2
dp[i]=dp[i]%mod;
continue;
}
if(s[i-1]=='*'&&s[i-2]>'0'&&s[i-2]<='2'){
if(s[i-2]=='1')
dp[i]+=((9*(dp[i-2]%mod)%mod));
else if(s[i-2]=='2')
dp[i]+=((6*(dp[i-2]%mod))%mod);//s[i-2]==2
dp[i]=dp[i]%mod;
continue;
}
if(s[i-2]=='*'&&s[i-1]=='*'){
dp[i]+=(((dp[i-2]%mod)*15)%mod);
dp[i]=dp[i]%mod;
continue;
}
}
return dp[n];
}