马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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]
|