Skip to content

Commit eea1160

Browse files
committed
decode-ways solution
1 parent 6498391 commit eea1160

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

decode-ways/i-mprovising.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Time complexity O(n)
3+
Space complexity O(1)
4+
5+
Dynamic programming
6+
"""
7+
8+
9+
class Solution:
10+
def numDecodings(self, s: str) -> int:
11+
if s[0] == '0':
12+
return 0
13+
n = len(s)
14+
if n == 1:
15+
return 1
16+
tmp = int(s[:2])
17+
dp = [1, 1]
18+
if 11 <= tmp <= 26:
19+
if tmp != 20:
20+
dp = [1, 2]
21+
elif s[1] == '0':
22+
if tmp not in [10, 20]:
23+
return 0
24+
if n == 2:
25+
return dp[-1]
26+
27+
for i in range(2, n):
28+
if s[i] == '0':
29+
if s[i-1] in ['1', '2']:
30+
cur = dp[0]
31+
else:
32+
return 0
33+
else:
34+
cur = dp[1]
35+
tmp = int(s[i-1:i+1])
36+
if (11 <= tmp <= 26) and (tmp != 20):
37+
cur += dp[0]
38+
dp = [dp[1], cur]
39+
40+
return dp[-1]

0 commit comments

Comments
 (0)