鱼C论坛

 找回密码
 立即注册
查看: 2795|回复: 0

[学习笔记] Leetcode 639. Decode Ways II

[复制链接]
发表于 2020-9-25 10:43:16 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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:
The length of the input string will fit in range [1, 105].
The input string will only contain the character '*' and digits '0' - '9'.
class Solution:
    def numDecodings(self, s: str) -> int:
        MOD = 1000000007
        n = len(s)
        dp = [0 for _ in range(n + 1)]
        dp[0] = 1
        
        def getCnt(c):
            if c == '0': return 0
            if c == '*': return 9
            return 1
        
        def getCnt2(c2, c1):
            if c2 == '0' or (c2 >= '3' and c2 <= '9'): return 0
            if c2 == '1':
                if c1 == '*': return 9
                else: return 1
            if c2 == '2':
                if c1 >= '0' and c1 <= '6': return 1
                if c1 >= '7' and c1 <= '9': return 0
                return 6
            
            if c1 >= '0' and c1 <= '6': return 2
            if c1 >= '7' and c1 <= '9': return 1
            return 15
        
        for i in range(1, n + 1):
            dp[i] = 0
            c = getCnt(s[i - 1])
            dp[i] += c * dp[i - 1]
            
            if i > 1:
                c = getCnt2(s[i - 2], s[i - 1])
                dp[i] += c * dp[i - 2]
            
            dp[i] = dp[i] % MOD
        
        return dp[n]

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-22 08:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表