Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab"
,
Return 1
since the palindrome partitioning ["aa","b"]
could be produced using 1 cut.
只说DP解法好了。
1、建立cut[n]来保存每一个字符处能切次数的最小值,如果s[j, i]是回文,那么cut[i] = cut[j - 1]+1
2、建立isPalindrome[n][n]数组保存s[j, i]是不是回文,如果s[j, i]是回文,那么肯定s[j] == s[i],而且isPalindrome[j+1][i-1]==true,这时候就需要更新cut[i] = cut[j-1]
代码如下:
public class Solution {
public int minCut(String s) {
int len = s.length();
int[] cut = new int[len];
boolean[][] isPalindrome = new boolean[len][len];
char[] cs = s.toCharArray();
for (int i = 0; i < len; i ++) {
int min = i;
for (int j = 0; j <= i; j ++) {
if (cs[i] == cs[j] && (j + 1 > i -1 || isPalindrome[j + 1][i - 1])) {
isPalindrome[j][i] = true;
min = Math.min(min, j == 0? 0: cut[j - 1] + 1);
}
}
cut[i] = min;
}
return cut[len - 1];
}
}
另一种O(n)space的方法,不需要isPalindrome[n][n]数组,是遍历s[n],每次的s[i]向外发散,分为奇数序列和偶数序列两种情况,然后动态更新cut[i]也很巧妙,代码如下:
public class Solution {
public int minCut(String s) {
int n = s.length();
char cs[] = s.toCharArray();
int[] cut = new int[n + 1]; // number of cuts for the first k characters
for (int i = 0; i <= n; i++) cut[i] = i-1;
for (int i = 0; i < n; i++) {
for (int j = 0; i-j >= 0 && i+j < n && cs[i-j]==cs[i+j] ; j++) // odd length palindrome
cut[i+j+1] = Math.min(cut[i+j+1],1+cut[i-j]);
for (int j = 1; i-j+1 >= 0 && i+j < n && cs[i-j+1] == cs[i+j]; j++) // even length palindrome
cut[i+j+1] = Math.min(cut[i+j+1],1+cut[i-j+1]);
}
return cut[n];
}
}