鱼C论坛

 找回密码
 立即注册
查看: 3180|回复: 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'.

  1. class Solution:
  2.     def numDecodings(self, s: str) -> int:
  3.         MOD = 1000000007
  4.         n = len(s)
  5.         dp = [0 for _ in range(n + 1)]
  6.         dp[0] = 1
  7.         
  8.         def getCnt(c):
  9.             if c == '0': return 0
  10.             if c == '*': return 9
  11.             return 1
  12.         
  13.         def getCnt2(c2, c1):
  14.             if c2 == '0' or (c2 >= '3' and c2 <= '9'): return 0
  15.             if c2 == '1':
  16.                 if c1 == '*': return 9
  17.                 else: return 1
  18.             if c2 == '2':
  19.                 if c1 >= '0' and c1 <= '6': return 1
  20.                 if c1 >= '7' and c1 <= '9': return 0
  21.                 return 6
  22.             
  23.             if c1 >= '0' and c1 <= '6': return 2
  24.             if c1 >= '7' and c1 <= '9': return 1
  25.             return 15
  26.         
  27.         for i in range(1, n + 1):
  28.             dp[i] = 0
  29.             c = getCnt(s[i - 1])
  30.             dp[i] += c * dp[i - 1]
  31.             
  32.             if i > 1:
  33.                 c = getCnt2(s[i - 2], s[i - 1])
  34.                 dp[i] += c * dp[i - 2]
  35.             
  36.             dp[i] = dp[i] % MOD
  37.         
  38.         return dp[n]
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-5-13 02:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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