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.
前面一道题目是要找到所有的回文子字符组合,现在是找到最小的分割数。很显然,应该用动态规划优化。
开一个数组minValue, minValue[ i ] 存储以 index i 为起点的字符串的最小分割数。
同时开一个二维数组isPal, 用来存储string中子字符串是否为回文字符。( isPal [ i ] [ j ] = isPal [ i ] [ j ] && s [ i ] == s [ j ] )
运行时间:
代码:
public class PalindromePartitioningII {
public int minCut(String s) {
int[] minCache = new int[s.length()];
boolean[][] isPal = new boolean[s.length()][s.length()];
for (int i = s.length() - 1; i >= 0; i--) {
for (int j = i; j < s.length(); j++) {
if (( i + 1 > j - 1 || isPal[i + 1][j - 1]) && s.charAt(i)== s.charAt(j))
isPal[i][j] = true;
}
}
Arrays.fill(minCache, Integer.MAX_VALUE);
minCache[s.length() - 1] = 0;
return doPartition(minCache, isPal, s, 0);
}
private int doPartition(int[] minCache, boolean[][] isPal, String s, int begin) {
if (begin == s.length()) {
return 0;
}
if (minCache[begin] != Integer.MAX_VALUE) {
return minCache[begin];
}
int curMin = Integer.MAX_VALUE;
for (int i = begin; i < s.length(); i++) {
if (isPal[begin][i]) {
if (i == s.length() - 1) {
curMin = 0;
break;
}
curMin = Math.min(curMin, doPartition(minCache, isPal, s, i + 1) + 1);
}
}
minCache[begin] = curMin;
return minCache[begin];
}
}