forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0091-decode-ways.java
71 lines (65 loc) · 1.89 KB
/
0091-decode-ways.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Optimal
classSolution {
publicintnumDecodings(Strings) {
int[] dp = newint[s.length() + 1];
inttwoBack = 1; // empty string
intoneBack = s.charAt(0) == '0' ? 0 : 1;
intcurrent = oneBack;
for (inti = 2; i < s.length() + 1; i++) {
current = 0;
if (s.charAt(i - 1) != '0') {
current += oneBack;
}
if (
s.charAt(i - 2) == '1' ||
(s.charAt(i - 2) == '2' && s.charAt(i - 1) < '7')
) {
current += twoBack;
}
twoBack = oneBack;
oneBack = current;
}
returncurrent;
}
}
//bottom up
classSolution {
publicintnumDecodings(Strings) {
int[] dp = newint[s.length() + 1];
dp[0] = 1; // empty string
dp[1] = s.charAt(0) == '0' ? 0 : 1;
for (inti = 2; i < s.length() + 1; i++) {
if (s.charAt(i - 1) != '0') {
dp[i] += dp[i - 1];
}
if (
s.charAt(i - 2) == '1' ||
(s.charAt(i - 2) == '2' && s.charAt(i - 1) < '7')
) {
dp[i] += dp[i - 2];
}
}
returndp[s.length()];
}
}
//top down with memoization
classSolution {
publicintnumDecodings(Strings) {
returnnumDecodings(s, 0, newInteger[s.length()]);
}
privateintnumDecodings(Strings, inti, Integer[] dp) {
if (i == s.length()) return1;
if (s.charAt(i) == '0') return0;
if (dp[i] != null) returndp[i];
intcount = 0;
count += numDecodings(s, i + 1, dp);
if (
i < s.length() - 1 &&
(s.charAt(i) == '1' || s.charAt(i) == '2' && s.charAt(i + 1) < '7')
) {
count += numDecodings(s, i + 2, dp);
}
dp[i] = count;
returndp[i];
}
}