File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string } s
3+ * @return {number }
4+ */
5+
6+ var numDecodings = function ( s ) {
7+ if ( s == null || s . length === 0 ) {
8+ return 0 ;
9+ }
10+
11+ const n = s . length ;
12+ const dp = new Array ( n + 1 ) . fill ( 0 ) ;
13+ dp [ 0 ] = 1 ;
14+ dp [ 1 ] = s [ 0 ] === '0' ? 0 : 1 ;
15+
16+ for ( let i = 2 ; i <= n ; i ++ ) {
17+ const oneDigit = parseInt ( s . substring ( i - 1 , i ) ) ;
18+ const twoDigits = parseInt ( s . substring ( i - 2 , i ) ) ;
19+
20+ // Check if single digit decoding is possible
21+ if ( oneDigit >= 1 && oneDigit <= 9 ) {
22+ dp [ i ] += dp [ i - 1 ] ;
23+ }
24+
25+ // Check if two digit decoding is possible
26+ if ( twoDigits >= 10 && twoDigits <= 26 ) {
27+ dp [ i ] += dp [ i - 2 ] ;
28+ }
29+ }
30+
31+ return dp [ n ] ;
32+ } ;
33+
34+
35+ console . log ( numDecodings ( "12" ) ) ;
36+ console . log ( numDecodings ( "226" ) ) ;
37+ console . log ( numDecodings ( "06" ) ) ;
38+
39+ /*
40+ 시간 복잡도: O(n)
41+ 공간 복잡도: O(n)
42+ */
You can’t perform that action at this time.
0 commit comments