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.

Example 1:

Input: "*"
Output: 9
Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I".

Example 2:

Input: "1*"
Output: 9 + 9 = 18

Note:

  1. The length of the input string will fit in range [1, 105].
  2. The input string will only contain the character '*' and digits '0' - '9'.

题意大概是这么个意思:给一个只包含*和1-9的字符串,其中星号*可以任意替换为1-9。如果用A-Z表示1-26,那么找到给定字符串可以由多少种只由A-Z的字符串转换得到。

思路一:

首先考虑:一位数字可以表示一个字母,比如1-A,两位字符也可以表示一个字母比如26-Z。那么根据是1个或者2个字符表示1个字母很快可以想到一个DFS的思路。

      对于每个大于2个字符的字符串S[n],我们可以把它分解成两种情况:

     1. 前面n-2个字符的子串 和 最后两个字符的子串。

    2. 前面n-1个字符的子串 和 最后一个字符的子串。

    如果用nums()表示A-Z字符串可以匹配的个数,我们可以得到 

nums(S[1..n]) = nums(S[1...n-2] ) * nums(S[n-1,n])  +  nums(S[1...n-1] ) * nums(S[n]) .

    DFS 终止条件为:当要找的字符串长度小于3的时候,我们通过单独的分析一一列举出来。


思路二:

当一个题目可以被DFS搞定,接下来我们就得找找有没有对应的DP算法了。通过上文我们知道。S[1..n] 总是可以由 S[1...n-1] + S[1....n-2]推导出来。无非是多了个系数:中间再加上长度为1和2的字符串单独分析过程。Bingo,这不就是变形版的fibonacci数列问题吗!!

话不多说,直接上代码,参考lc大牛:

class Solution {
public:
    int numDecodings(string s) {
        int n = s.size(), p = 1000000007;
        // f2 is the answer to sub string ending at position i; Initially i = 0.
        long f1 = 1, f2 = helper(s.substr(0,1));
        // DP to get f2 for sub string ending at position n-1;
        for (int i = 1; i < n; i++) {
            long f3 = (f2*helper(s.substr(i, 1)))+(f1*helper(s.substr(i-1, 2)));
            f1 = f2;
            f2 = f3%p;
        }
        return f2;
    }
private:
    int helper(string s) {
        if (s.size() == 1) {
            if (s[0] == '*') return 9;
            return s[0] == '0'? 0:1;
        }
        // 11-26, except 20 because '*' is 1-9
        if (s == "**")  
            return 15;
        else if (s[1] =='*') {
            if (s[0] =='1') return 9;
            return s[0] == '2'? 6:0;
        }
        else if (s[0] == '*') 
            return s[1] <= '6'? 2:1;
        else 
            // if two digits, it has to be in [10 26]; no leading 0
            return stoi(s) >= 10 && stoi(s) <= 26? 1:0; 
    }
};

唯一的难点就在于一位长度和两位长度的字符串可组成个数的讨论过程,也就是helper函数过程,仔细分析一下应该不难。最后注意取下模。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值