File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
1
+ function numDecodings ( s : string ) : number {
2
+ const sLen = s . length ;
3
+ const isValid = ( s : string ) : boolean => {
4
+ if ( s [ 0 ] === "0" ) return false ;
5
+
6
+ return Number ( s ) > 0 && Number ( s ) <= 26 ;
7
+ } ;
8
+
9
+ if ( sLen === 0 ) return 0 ;
10
+ if ( s . length === 1 ) return isValid ( s [ 0 ] ) ? 1 : 0 ;
11
+
12
+ // dp[i]: i๋ฒ์งธ ์์น๊น์ง ๋์ฝ๋ฉํ ์ ์๋ ๋ฐฉ๋ฒ์ ์
13
+ const dp : number [ ] = Array ( sLen ) . fill ( 0 ) ;
14
+ dp [ 0 ] = isValid ( s [ 0 ] ) ? 1 : 0 ;
15
+ dp [ 1 ] = ( isValid ( s [ 1 ] ) ? dp [ 0 ] : 0 ) + ( isValid ( s . substring ( 0 , 2 ) ) ? 1 : 0 ) ;
16
+
17
+ for ( let i = 2 ; i < sLen ; i ++ ) {
18
+ const singleDigitWays = isValid ( s [ i ] ) ? dp [ i - 1 ] : 0 ;
19
+ const doubleDigitWays = isValid ( s [ i - 1 ] + s [ i ] ) ? dp [ i - 2 ] : 0 ;
20
+
21
+ dp [ i ] = singleDigitWays + doubleDigitWays ;
22
+ }
23
+
24
+ return dp [ sLen - 1 ] ;
25
+ }
You canโt perform that action at this time.
0 commit comments