File tree Expand file tree Collapse file tree 1 file changed +20
-22
lines changed Expand file tree Collapse file tree 1 file changed +20
-22
lines changed Original file line number Diff line number Diff line change @@ -26,32 +26,30 @@ public class SolutionSuffix {
2626
2727 // considering suffix: s[i: end]
2828 public int numDecodings (String s ) {
29- int len = s .length ();
30- if (len == 0 ) {
31- // for "", 0 ways to decode
29+ int n = s .length ();
30+ if (n == 0 ) {
3231 return 0 ;
3332 }
34- // dp[i] = decode ways for s[i:end]
35- int [] dp = new int [len + 1 ];
36-
37- // initialize dp[len] and dp[len-1]
38- dp [len ] = 1 ;
39- dp [len - 1 ] = s .charAt (len - 1 ) == '0' ? 0 : 1 ;
40-
41- for (int i = len - 2 ; i >= 0 ; i --) {
42- char ch = s .charAt (i );
43- if (ch != '0' ) {
44- if (Integer .parseInt (s .substring (i , i + 2 )) <= 26 ) {
45- // for [10-26]: decode as: [10-26] | decode(s[i+2],end)
46- // + decode as: [1-9] | decode(s[i+1],end)
47- dp [i ] = dp [i + 2 ] + dp [i + 1 ];
48- } else {
49- // for [27-99], decode as: [2-9] | decode(s[i+1,end])
50- dp [i ] = dp [i + 1 ];
33+ int [] f = new int [n + 1 ];
34+ for (int i = n ; i >= 0 ; i --) {
35+ int count = 0 ;
36+ if (i == n ) {
37+ count = 1 ;
38+ } else {
39+ int num1 = s .charAt (i ) - '0' ;
40+ if (num1 > 0 && num1 < 10 ) {
41+ count = f [i + 1 ];
42+ }
43+ if (i + 1 < n ) {
44+ int num2 = s .charAt (i + 1 ) - '0' + 10 * num1 ;
45+ if (num2 >= 10 && num2 <= 26 ) {
46+ count += f [i + 2 ];
47+ }
5148 }
5249 }
53- // if ch == '0', dp [i] = 0
50+ f [i ] = count ;
5451 }
55- return dp [0 ];
52+ return f [0 ];
5653 }
54+
5755}
You can’t perform that action at this time.
0 commit comments