File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ // TC: O(N)
2
+ // SC: O(N)
3
+
4
+ /**
5
+ * @param {string } s
6
+ * @return {number }
7
+ */
8
+ var numDecodings = function ( s ) {
9
+ if ( s [ 0 ] === "0" ) {
10
+ return 0 ;
11
+ }
12
+ if ( s . length === 1 ) {
13
+ return 1 ;
14
+ }
15
+
16
+ const dpTable = new Array ( s . length ) . fill ( 0 ) ;
17
+ if ( s [ 0 ] !== "0" ) {
18
+ dpTable [ 0 ] = 1 ;
19
+ }
20
+ if ( s [ 1 ] !== "0" ) {
21
+ dpTable [ 1 ] += 1 ;
22
+ }
23
+ if ( isValid ( `${ s [ 0 ] } ${ s [ 1 ] } ` ) ) {
24
+ dpTable [ 1 ] += 1 ;
25
+ }
26
+
27
+ for ( let index = 2 ; index < s . length ; index ++ ) {
28
+ if ( s [ index ] !== "0" ) {
29
+ dpTable [ index ] += dpTable [ index - 1 ] ;
30
+ }
31
+ if ( s [ index - 1 ] !== "0" && isValid ( `${ s [ index - 1 ] } ${ s [ index ] } ` ) ) {
32
+ dpTable [ index ] += dpTable [ index - 2 ] ;
33
+ }
34
+ }
35
+
36
+ return dpTable [ dpTable . length - 1 ] ;
37
+
38
+ function isValid ( stringNumber ) {
39
+ const number = Number ( stringNumber ) ;
40
+ if ( number <= 0 ) {
41
+ return false ;
42
+ }
43
+ if ( 27 <= number ) {
44
+ return false ;
45
+ }
46
+ return true ;
47
+ }
48
+ } ;
You can’t perform that action at this time.
0 commit comments