Decode Ways II LeetCode solution in Python

1
# Runtime: 180 ms (Top 97.4%) | Memory: 21.20 MB (Top 53.7%)
2

3

4
class Solution:
5
def numDecodings(self, s: str):
6
if s[0] == "0":
7
return 0
8
cMap = {
9
"0": 0,
10
"*": 9,
11
"**": 15,
12
"1*": 9,
13
"2*": 6,
14
} # {char(s) : multiplier} mapping
15
for i in range(1, 27):
16
cMap[str(i)] = 1
17
for i in range(0, 7):
18
cMap["*" + str(i)] = 2
19
for i in range(7, 10):
20
cMap["*" + str(i)] = 1
21

22
dp = [0] * (len(s) + 1)
23
dp[0], dp[-1] = cMap[s[0]], 1
24

25
for i in range(1, len(s)):
26
dp[i] += (
27
cMap[s[i]] * dp[i - 1] + cMap.get(s[i - 1 : i + 1], 0) * dp[i - 2]
28
) % (10**9 + 7)
29
if not dp[i]:
30
return 0
31

32
return dp[-2]

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0