File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n), n: s.length()
2+ // Space Complexity: O(n), n: s.length()
3+ class Solution {
4+ public int numDecodings (String s ) {
5+ if (s .length () == 0 ) { // edge case
6+ return 0 ;
7+ }
8+
9+ int length = s .length ()+1 ;
10+ int [] cntArr = new int [length ]; // using dynamic programming
11+
12+ // check the case i == 0, i == 1 first
13+ cntArr [0 ] = 1 ;
14+ if (s .charAt (0 ) != '0' ) {
15+ cntArr [1 ] = 1 ;
16+ }
17+
18+ for (int i = 2 ; i < length ; ++i ) {
19+ char ch = s .charAt (i -1 );
20+ if (ch != '0' ) { // check for 1-9
21+ cntArr [i ] += cntArr [i -1 ];
22+ }
23+
24+ // check for 10-26
25+ int num = (s .charAt (i -2 )-'0' ) * 10 + (ch -'0' );
26+ if (num >= 10 && num <= 26 ) {
27+ cntArr [i ] += cntArr [i -2 ];
28+ }
29+ }
30+
31+ return cntArr [length -1 ];
32+ }
33+ }
You can’t perform that action at this time.
0 commit comments