We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 6498391 commit eea1160Copy full SHA for eea1160
decode-ways/i-mprovising.py
@@ -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
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
33
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
0 commit comments