Question
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.
code
/**
* DP方式解决
*
* @param s
* @return
*/
public int minCut(String s) {
if (s == null || s.length() == 0) {
return 0;
}
boolean[][] flag = new boolean[s.length()][s.length()];
int[] len = new int[s.length() + 1];
len[0] = -1;
for (int i = 1; i <= s.length(); i++) {
len[i] = Integer.MAX_VALUE;
for (int j = 0; j < i; j++) {
flag[j][i - 1] = s.charAt(j) == s.charAt(i - 1) && (i - j <= 2 || flag[j + 1][i - 2]);
if (flag[j][i - 1]) {
len[i] = Math.min(len[i], len[j] + 1);
}
}
}
return len[s.length()];
}
本文介绍了一种使用动态规划方法来解决字符串最小回文分割的问题,给出了一段示例代码,该代码可以计算出将字符串分割成全部为回文子串所需的最少切割次数。
276

被折叠的 条评论
为什么被折叠?



