Skip to content

Commit 2358623

Browse files
committed
add decode ways solution
1 parent 6783b72 commit 2358623

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

decode-ways/Tessa1217.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
주어진 문자열을 복호화 할 수 있는 경우의 수를 반환하시오.
3+
문자열은 A-Z까지 숫자 1-26으로 치환
4+
예시: "AAJF" => (1, 1, 10, 6), (11, 10, 6)...
5+
*/
6+
class Solution {
7+
8+
// 시간복잡도: O(n), 공간복잡도: O(n)
9+
public int numDecodings(String s) {
10+
11+
int[] dp = new int[s.length() + 1];
12+
13+
// contain leading zero(s)
14+
if (s.charAt(0) == '0') {
15+
return 0;
16+
}
17+
18+
dp[0] = 1;
19+
dp[1] = 1;
20+
21+
for (int i = 2; i <= s.length(); i++) {
22+
23+
// 1자리수 검사
24+
int one = Integer.parseInt(Character.toString(s.charAt(i - 1)));
25+
26+
if (one != 0) {
27+
dp[i] += dp[i - 1];
28+
}
29+
30+
// 2자리수 검사
31+
int two = Integer.parseInt(Character.toString(s.charAt(i - 2))) * 10 + one;
32+
33+
if (two >= 10 && two <= 26) {
34+
dp[i] += dp[i - 2];
35+
}
36+
37+
}
38+
39+
return dp[s.length()];
40+
}
41+
42+
}
43+

0 commit comments

Comments
 (0)