Skip to content

Commit 25c2f1e

Browse files
committed
091 (3) update suffix solution
1 parent acc190b commit 25c2f1e

File tree

1 file changed

+20
-22
lines changed

1 file changed

+20
-22
lines changed

src/_091_DecodeWays/SolutionSuffix.java

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy