Skip to content

Commit 4fc1a92

Browse files
committed
[LC] feat: 240825 decode ways
1 parent 5dd8db8 commit 4fc1a92

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

decode-ways/hajunyoo.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution:
2+
# time complexity: O(n)
3+
# space complexity: O(n)
4+
def numDecodings(self, s: str) -> int:
5+
if not s or s.startswith('0'):
6+
return 0
7+
8+
n = len(s)
9+
dp = [0] * (n + 1)
10+
dp[0] = 1
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+
dp[i] += dp[i - 1]
16+
17+
two_digit = int(s[i - 2:i])
18+
if 10 <= two_digit <= 26:
19+
dp[i] += dp[i - 2]
20+
21+
return dp[n]

0 commit comments

Comments
 (0)