Skip to content

Commit 6d1adcd

Browse files
committed
solve: decode ways
1 parent 03f2433 commit 6d1adcd

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

decode-ways/evan.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
def numDecodings(s: str) -> int:
2+
if not s:
3+
return 0
4+
5+
n = len(s)
6+
7+
# dp[i] represents the number of ways to decode the string s[:i]
8+
dp = [0] * (n + 1)
9+
dp[0] = 1
10+
11+
dp[1] = 1 if s[0] != "0" else 0
12+
13+
for i in range(2, n + 1):
14+
if s[i - 1] != "0":
15+
# If the one-digit number is valid, we can decode it
16+
dp[i] += dp[i - 1]
17+
18+
two_digit = int(s[i - 2 : i])
19+
20+
if 10 <= two_digit <= 26:
21+
# If the two-digit number is valid, we can decode it
22+
dp[i] += dp[i - 2]
23+
24+
return dp[n]

0 commit comments

Comments
 (0)