LeetCode 639. Decode Ways II

题意

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()];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值