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:
The length of the input string will fit in range .
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 =
dp = 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 = 0
c = getCnt(s)
dp += c * dp
if i > 1:
c = getCnt2(s, s)
dp += c * dp
dp = dp % MOD
return dp
页:
[1]