Skip to content

Commit 1c68147

Browse files
committed
Add solution for Decode Ways problem
1 parent 998a10b commit 1c68147

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

decode-ways/KwonNayeon.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
Conditions:
3+
- 1 <= s.length <= 100
4+
- s contains only digits and may contain leading zero(s).
5+
6+
Time Complexity: O(n)
7+
- 각 문자를 한 번씩만 방문함 (문자열의 길이: n)
8+
9+
Space Complexity: O(n)
10+
- dp 배열의 크기는 n+1
11+
- 이 배열 이외에 추가 공간을 사용하지 않음
12+
13+
Base cases:
14+
- If string is empty or starts with '0', return 0 (impossible to decode)
15+
16+
Dynamic Programming approach:
17+
- dp[i] represents the number of ways to decode first i characters
18+
- dp array has size n+1 to include the empty string case (dp[0])
19+
- For each position, consider both single-digit and two-digit decodings
20+
21+
메모:
22+
- 다른 dp문제 풀어보기
23+
"""
24+
class Solution:
25+
def numDecodings(self, s: str) -> int:
26+
if not s or s[0] == '0':
27+
return 0
28+
29+
n = len(s)
30+
dp = [0] * (n + 1)
31+
dp[0] = 1
32+
33+
for i in range(1, n + 1):
34+
if s[i-1] != '0':
35+
dp[i] += dp[i-1]
36+
37+
if i > 1 and s[i-2] != '0':
38+
two_digit = int(s[i-2:i])
39+
if 1 <= two_digit <= 26:
40+
dp[i] += dp[i-2]
41+
42+
return dp[n]

0 commit comments

Comments
 (0)