LeetCode #639 Decode Ways II 解码方法 II

639 Decode Ways II 解码方法 II

Description:
A message containing letters from A-Z can be encoded into numbers using the following mapping:

'A' -> "1"
'B' -> "2"
...
'Z' -> "26"

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:

"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".

In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1" is equivalent to decoding any of the encoded messages it can represent.

Given a string s containing digits and the '*' character, return the number of ways to decode it.

Since the answer may be very large, return it modulo 10^9 + 7.

Example:

Example 1:

Input: s = ""
Output: 9
Explanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9".
Each of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively.
Hence, there are a total of 9 ways to decode "
".

Example 2:

Input: s = "1"
Output: 18
Explanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19".
Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K").
Hence, there are a total of 9 * 2 = 18 ways to decode "1
".

Example 3:

Input: s = "2"
Output: 15
Explanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29".
"21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way.
Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2
".

Constraints:

1 <= s.length <= 10^5
s[i] is a digit or '*'.

题目描述:
一条包含字母 A-Z 的消息通过以下的方式进行了编码:

'A' -> 1
'B' -> 2
...
'Z' -> 26

除了上述的条件以外,现在加密字符串可以包含字符 '*'了,字符'*'可以被当做1到9当中的任意一个数字。

给定一条包含数字和字符'*'的加密信息,请确定解码方法的总数。

同时,由于结果值可能会相当的大,所以你应当对10^9 + 7取模。(翻译者标注:此处取模主要是为了防止溢出)

示例 :

示例 1 :

输入: "*"
输出: 9
解释: 加密的信息可以被解密为: "A", "B", "C", "D", "E", "F", "G", "H", "I".

示例 2 :

输入: "1"
输出: 9 + 9 = 18(翻译者标注:这里1
可以分解为1,* 或者当做1*来处理,所以结果是9+9=18)

说明:

输入的字符串长度范围是 [1, 10^5]。
输入的字符串只会包含字符 '*' 和 数字'0' - '9'。

思路:

动态规划
dp[i] 表示前 i 个字符能够形成的解码方法总数
dp[i] = dp[i - 1] * a + dp[i - 2] * b
其中 a = s[i] == '*' ? 9 : (s[i] != '0'), 表示当前的字符如果为 , 有 9 种取法(1 - 9), 如果为 0 则为 0, 否则为 1; b 则需要再往前看一位, 如果 s[i - 1] == '1', 则一定可以和当前位置组合, b = a + (a == 0), 如果 s[i - 1] == '2', 则要求当前位要么是 '0'-'7', 要么是 '' 才能组合, 其余情况都为 0
可以看出只需要常数个变量即可
时间复杂度 O(n), 空间复杂度 O(1)

代码:
C++:

class Solution 
{
public:
    int numDecodings(string s) 
    {
        long result = s[0] == '*' ? 9 : (s[0] != '0'), pre = 1;
        for (int i = 1, n = s.size(), a = 0, b = 0, mod = 1e9 + 7; i < n; i++)
        {
            a = s[i] == '*' ? 9 : (s[i] != '0');
            switch (s[i - 1])
            {
                case '1':
                    b = a + (a == 0);
                    break;
                case '2':
                    b = s[i] == '*' ? 6 : s[i] < '7' ? 1 : 0;
                    break;
                case '*':
                    b = a + (a == 0) + (s[i] == '*' ? 6 : s[i] < '7' ? 1 : 0);
                    break;
                default:
                    b = 0;
            }
            pre = (result * a + pre * b) % mod;
            swap(result, pre);
        }
        return result;
    }
};

Java:

class Solution {
    public int numDecodings(String s) {
        long result = s.charAt(0) == '*' ? 9 : (s.charAt(0) == '0' ? 0 : 1), pre = 1, cur = 0;
        int n = s.length(), mod = 1000000007;
        for (int i = 1, a = 0, b = 0; i < n; i++) {
            a = s.charAt(i) == '*' ? 9 : (s.charAt(i) == '0' ? 0 : 1);
            switch (s.charAt(i - 1)) {
                case '1':
                    b = a + (a == 0 ? 1 : 0);
                    break;
                case '2':
                    b = (s.charAt(i) == '*' ? 6 : (s.charAt(i) < '7' ? 1 : 0));
                    break;
                case '*':
                    b = a + (a == 0 ? 1 : 0) + (s.charAt(i) == '*' ? 6 : (s.charAt(i) < '7' ? 1 : 0));
                    break;
                default:
                    b = 0;
            }
            cur = (result * a + pre * b) % mod;
            pre = result;
            result = cur;
        }
        return (int)result;
    }
}

Python:

class Solution:
    def numDecodings(self, s: str) -> int:
        result, pre = 9 if s[0] == '*' else s[0] != '0', 1
        for i in range(1, len(s)):
            a = 9 if s[i] == '*' else s[i] != '0'
            b = (a + (not a) if s[i - 1] == '1' or s[i - 1] == '*' else 0) + (6 if s[i] == '*' else 1 if s[i] < '7' else 0) * (s[i - 1] == '2' or s[i - 1] == '*')
            result, pre = a * result + b * pre, result
        return result % (10 ** 9 + 7)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容