Skip to content

Commit d8ddf63

Browse files
committed
decode-ways solution
1 parent ca3c33e commit d8ddf63

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

β€Ždecode-ways/hyeri0903.javaβ€Ž

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
public int numDecodings(String s) {
3+
/**
4+
1.문제: decode ν•  수 μžˆλŠ” λͺ¨λ“  경우의 수 return
5+
2.쑰건:
6+
- μ—¬λŸ¬ 개의 경우의 수 μžˆμ„ 수 μžˆλ‹€.
7+
- decode λΆˆκ°€λŠ₯ν•œ κ²½μš°κ°€ μžˆμ„ 수 μžˆλ‹€.
8+
- λͺ¨λ‘ λΆˆκ°€λŠ₯ν•œ 경우 return 0
9+
3.풀이
10+
- dp (해석할 수 μžˆλŠ” 방법 수λ₯Ό λˆ„μ ν•΄μ„œ 더함)
11+
e.g 226
12+
0자리 : dp[0] = 0
13+
1자리(2) : 2 -> dp]1] = 1
14+
2자리(22): 2(B), 22(v) -> dp[2] = 2
15+
3자리(226): (2, 2, 6), (22, 6), (2, 26) -> dp[3] = 3
16+
17+
time complexity: O(N)
18+
space complexity: O(N)
19+
20+
*/
21+
if (s.charAt(0) == '0') {
22+
return 0;
23+
}
24+
int n = s.length();
25+
int[] dp = new int[n+1];
26+
dp[0] = 1; //아무것도 μ—†λŠ” μƒνƒœ
27+
dp[1] = 1;
28+
29+
for(int i = 2; i<=n; i++) {
30+
//1자리수
31+
if (s.charAt(i-1) != '0') {
32+
dp[i] += dp[i-1];
33+
}
34+
//2자리수
35+
if(i > 1) {
36+
int number = Integer.parseInt(s.substring(i-2, i));
37+
//2자리 μˆ˜λŠ” 10 ~ 26μ‚¬μ΄λ§Œ κ°€λŠ₯
38+
if (number >= 10 && number <= 26) {
39+
dp[i] += dp[i-2];
40+
}
41+
}
42+
}
43+
return dp[n];
44+
}
45+
}

0 commit comments

Comments
Β (0)