您的位置:首页 > 其它

639. Decode Ways II

2018-01-14 03:05 357 查看
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
;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息