File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int numDecodings (String s ) {
3+ if (s == null || s .length () == 0 || s .charAt (0 ) == '0' ) {
4+ return 0 ;
5+ }
6+
7+ int n = s .length ();
8+ int [] dp = new int [n + 1 ];
9+
10+ dp [0 ] = 1 ; // λΉ λ¬Έμμ΄μ ν΄μνλ κ²½μ°μ μλ 1
11+ dp [1 ] = 1 ; // 첫 κΈμκ° '0'μ΄ μλμ μμμ 체ν¬νμΌλ―λ‘ 1 νμ
12+
13+ // 2. DP μν (Bottom-Up)
14+ for (int i = 2 ; i <= n ; i ++) {
15+ // νμ¬ λ¬Έμμ λ°λ‘ μ λ¬Έμ μΆμΆ
16+ // DP μΈλ±μ€ iλ λ¬Έμμ΄μ iλ²μ§Έ κΈμ(μΈλ±μ€ i-1)λ₯Ό μλ―Έν¨
17+ char current = s .charAt (i - 1 );
18+ char prev = s .charAt (i - 2 );
19+
20+ // Case 1: ν μ리 μ«μ ν΄μ (1 ~ 9)
21+ // νμ¬ μ«μκ° '1'~'9'λΌλ©΄, λ°λ‘ μ§μ λ¨κ³(i-1)μ κ²½μ°μ μλ₯Ό κ³μΉ
22+ if (current >= '1' && current <= '9' ) {
23+ dp [i ] += dp [i - 1 ];
24+ }
25+
26+ // Case 2: λ μ리 μ«μ ν΄μ (10 ~ 26)
27+ // μ΄μ μ«μμ ν©μ³μ κ°μ κ³μ°
28+ int twoDigit = (prev - '0' ) * 10 + (current - '0' );
29+
30+ if (twoDigit >= 10 && twoDigit <= 26 ) {
31+ dp [i ] += dp [i - 2 ];
32+ }
33+ }
34+
35+ // 3. κ²°κ³Ό λ°ν
36+ return dp [n ];
37+ }
38+ }
You canβt perform that action at this time.
0 commit comments