File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Arrays ;
2
+
3
+
4
+ class Solution {
5
+
6
+ // 11106
7
+ // 가장 큰 수는 2자리 이므로 한 번에 갈 수 있는 칸은 1~2칸
8
+ // 현재 칸이 0일 경우는 칸 이동 불가
9
+ // 코드 범위는 1~26
10
+
11
+ int stringSize = 0 ;
12
+ int [] dp ;
13
+
14
+ // DP 이용
15
+ public int numDecodings (String s ) {
16
+ stringSize = s .length ();
17
+ dp = new int [stringSize + 1 ];
18
+ Arrays .fill (dp , -1 );
19
+ return numDecodingHelper (s .toCharArray (), 0 );
20
+ }
21
+
22
+ // dp -> O(N)
23
+ private int numDecodingHelper (char [] s , int curIndex ) {
24
+ if (stringSize == curIndex ) return 1 ;
25
+ if (s [curIndex ] == '0' ) return 0 ; // 현재 칸이 0 -> 전진 불가
26
+ if (dp [curIndex ] != -1 ) return dp [curIndex ];
27
+
28
+ dp [curIndex ] = 0 ; // 현재 노드 방문 체크
29
+ dp [curIndex ] += numDecodingHelper (s , curIndex + 1 ); // 한 칸 전진
30
+
31
+ if ((curIndex + 1 < stringSize ) && checkRange (s [curIndex ], s [curIndex + 1 ])) // 2자리 코드가 10~26 안에 들어간다면
32
+ dp [curIndex ] += numDecodingHelper (s , curIndex + 2 ); // 2칸 전진
33
+
34
+ return dp [curIndex ];
35
+ }
36
+
37
+ private boolean checkRange (char left , char right ) {
38
+ int leftNum = left - '0' ;
39
+ int rightNum = right - '0' ; // 숫자로 변환
40
+
41
+ int num = leftNum * 10 + rightNum ;
42
+ return (num >= 10 && num <= 26 );
43
+ }
44
+ }
You can’t perform that action at this time.
0 commit comments