-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_132.java
More file actions
55 lines (50 loc) · 1.57 KB
/
Copy pathP_132.java
File metadata and controls
55 lines (50 loc) · 1.57 KB
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
package leetcode.hard;
public class P_132 {
static boolean[][] isPalindrome;
static boolean[] seen;
static int[] dp;
public int minCut(String s) {
final int n = s.length();
isPalindrome = new boolean[n][n];
seen = new boolean[n];
dp = new int[n];
for (int j = 0; j < n; j++) {
for (int i = 0; i <= j; i++) {
isPalindrome[i][j] = s.charAt(i) == s.charAt(j) && (j - i <= 2 || isPalindrome[i + 1][j - 1]);
}
}
return dfs(s.toCharArray(), 0) - 1;
}
private static int dfs(char[] w, int idx) {
if (idx == w.length) {
return 0;
}
if (seen[idx]) {
return dp[idx];
}
int res = (int) 1e9;
for (int i = idx; i < w.length; i++) {
if (isPalindrome[idx][i]) {
res = Math.min(res, 1 + dfs(w, i + 1));
}
}
seen[idx] = true;
return dp[idx] = res;
}
public static int minCutTopDown(String s) {
final int n = s.length();
final int[] dp = new int[n];
final boolean[][] isPalindrome = new boolean[n][n];
for (int j = 0; j < n; j++) {
int curr = j;
for (int i = 0; i <= j; i++) {
isPalindrome[i][j] = s.charAt(i) == s.charAt(j) && (j - i <= 2 || isPalindrome[i + 1][j - 1]);
if (isPalindrome[i][j]) {
curr = i == 0 ? 0 : Math.min(curr, dp[i - 1] + 1);
}
}
dp[j] = curr;
}
return dp[n - 1];
}
}