File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ # Time Complexity: O(n)
3+ # Space Complexity: O(n)
4+ */
5+ class Solution {
6+
7+ private boolean check12 (char ch ) {
8+ return (ch == '1' || ch == '2' );
9+ }
10+
11+ private boolean check1 (char ch ) {
12+ return ch == '1' ;
13+ }
14+
15+ private boolean check2 (char ch ) {
16+ return ch == '2' ;
17+ }
18+
19+ private boolean check0 (char ch ) {
20+ return ch == '0' ;
21+ }
22+
23+ private boolean check6 (char ch ) {
24+ return ch <= '6' ;
25+ }
26+
27+ public int numDecodings (String s ) {
28+ int n = s .length ();
29+
30+ if (n == 0 )
31+ return 0 ;
32+
33+ int [] dp = new int [n + 1 ];
34+
35+ if (check0 (s .charAt (0 )))
36+ return 0 ;
37+
38+ dp [0 ] = 1 ;
39+ dp [1 ] = 1 ;
40+ if (n == 1 )
41+ return dp [1 ];
42+
43+ for (int i = 1 ; i < n ; i ++) {
44+ if (check0 (s .charAt (i )) && !check12 (s .charAt (i - 1 )))
45+ return 0 ;
46+
47+ if (!check0 (s .charAt (i )))
48+ dp [i + 1 ] = dp [i ];
49+
50+ if (check1 (s .charAt (i - 1 )) || (check6 (s .charAt (i )) && check2 (s .charAt (i - 1 ))))
51+ dp [i + 1 ] += dp [i - 1 ];
52+ }
53+ return dp [n ];
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments