题意
A message containing letters from A-Z is being encoded to numbers using the following mapping way:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Beyond that, now the encoded string can also contain the character ‘*’, which can be treated as one of the numbers from 1 to 9.
Given the encoded message containing digits and the character ‘*’, return the total number of ways to decode it.
Also, since the answer may be very large, you should return the output mod 109 + 7.
解法
dp【i】表示前i的串有多少种decode的方法
然后分两个数一次decode,还是一个数decode,dp【i】从dp【i-1】和dp【i-2】转移而来。
代码:
注意几组数据:
*1*1*10
**
104
0
long long dp[100010];
const int MOD = 1e9 + 7;
int numDecodings(string s) {
dp[0] = 1;
dp[1] = s[0] == '*' ? 9 : 1;
if (s[0] == '0') {
dp[1] = 0;
}
for (int i = 2; i <= s.size(); i++) {
dp[i] = 0;
if (s[i - 1] == '*') {
dp[i] += dp[i - 1] * 9 % MOD;
dp[i] %= MOD;
}
else if(s[i-1] != '0'){
dp[i] += dp[i - 1];
dp[i] %= MOD;
}
if (s[i - 2] == '0')continue;
if (s[i - 1] == '*' && s[i - 2] == '*') {
dp[i] += dp[i - 2] * 15 % MOD;
dp[i] %= MOD;
}
else if (s[i - 1] == '*') {
if (s[i - 2] == '1') {
dp[i] += dp[i - 2] * 9 %MOD;
dp[i] %= MOD;
}
else if (s[i - 2] == '2') {
dp[i] += dp[i - 2] * 6 % MOD;
dp[i] %= MOD;
}
}
else if (s[i - 2] == '*') {
if (s[i - 1] > '6') {
dp[i] += dp[i - 2];
dp[i] %= MOD;
}
else {
dp[i] += dp[i - 2] * 2;
dp[i] %= MOD;
}
}
else {
if (s[i - 1] - '0' + (s[i - 2] - '0') * 10 <= 26) {
dp[i] += dp[i - 2];
dp[i] %= MOD;
}
}
}
return dp[s.size()];
}