Thought: DP. f(i) = 1 + min(f(j)) where palindrome(i, j) = true.
Code:
public class Solution {
public int minCut(String s) {
if (s.length() == 0) return 0;
boolean[][] palindrome = new boolean[s.length()][s.length()];
for (int j = s.length() - 1; j >= 0; j--) {
for (int i = 0; i <= j; i++) {
palindrome[j][i] = true;
}
}
for (int j = s.length() - 2; j >= 0; j--) {
for (int i = j + 1; i < s.length(); i++) {
palindrome[j][i] = palindrome[j + 1][i - 1] && (s.charAt(j) == s.charAt(i));
}
}
int[] result = new int[s.length() + 1];
result[0] = -1;
for (int i = 2; i <= s.length(); i++) {
int min = Integer.MAX_VALUE;
for (int j = 1; j <= i; j++) {
if (palindrome[j - 1][i - 1]) {
min = Math.min(min, result[j - 1]);
}
}
result[i] = 1 + min;
}
return result[s.length()];
}
}
No comments:
Post a Comment