Skip to content

Commit 857d78f

Browse files
committed
feat solve decode-ways
1 parent 680ac3a commit 857d78f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

decode-ways/pmjuu.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
def numDecodings(self, s: str) -> int:
3+
if s[0] == "0":
4+
return 0
5+
6+
prev, curr = 1, 1
7+
8+
for i in range(1, len(s)):
9+
temp = curr
10+
11+
if s[i] == "0":
12+
if s[i - 1] in ("1", "2"):
13+
curr = prev
14+
else:
15+
return 0
16+
else:
17+
two_num = int(s[i - 1] + s[i])
18+
is_two_num_decoded = 10 <= two_num <= 26
19+
if is_two_num_decoded:
20+
curr += prev
21+
22+
prev = temp
23+
24+
return curr
25+
26+
27+
# Time Complexity: O(n)
28+
# - The loop iterates through the string once, where n is the length of the string.
29+
30+
# Space Complexity: O(1)
31+
# - Only two variables (prev and curr) are used, independent of the input size.

0 commit comments

Comments
 (0)