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.
1) 初次尝试:在解决这个问题的时候,我第一反映是用贪婪算法,从头到尾遍历s,找出回文,但是事实上这样得不到最少的分割。例如:
ababbbabbaba
贪心算法得到的结果将是:aba,bbb,abba,b,a
函数返回的结果是4,即需要4次分割。但是更少的分割:
aba,b,bbabb,aba
需要三次分割。
2) 重新思考这个问题,翻阅了“算法导论”的动态规划章节,发现这个求最优解的问题也可以用动态规划的方法解决。
-----------------------------------------------------------------
input:
x[0...n-1],
c(x, i):
minimum cuts needed for a palindrome partitioning of x[0...i], initialize to be MAX.INT
recursion:
c(x, i) = min{c(x, j) + 1, c(x, i)}, 0 ≤ i < j ≤ n-1, if c[i...j] is a palindrome
return:
c(x, n-1): minimum cuts needed for a palindrome partitioning of x, also the return value,
dp[i, j]:
= true, if x[i...j] is palindrome; = false, else
-----------------------------------------------------------------
package Palindrome.Partitioning.II; public class net_ex1 { public int minCut(String s) { // Start typing your Java solution below // DO NOT write main() function int n = s.length(); // cut[i]表示s[i..n-1]需要的最小的切割 // p[i][j]表示s[i..j]是否是回文 int cut[] = new int[n + 1]; boolean p[][] = new boolean[n][n]; for (int i = 0; i < n; i++) { cut[i] = Integer.MAX_VALUE; p[i][i] = true;// 肯定是回文 } cut[n] = -1; for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { p[i][j] = ((s.charAt(i) == s.charAt(j)) && (j - i + 1 <= 2 || p[i + 1][j - 1]));// 判断回文,也是一个递归 if (p[i][j]) { cut[i] = Math.min(cut[i], cut[j + 1] + 1); } } } return cut[0]; } public static void main(String args[]) { String t1 = "adabdcaebdcebdcacaaaadbbcadabcbeabaadcbcaaddebdbddcbdacdbbaedbdaaecabdceddccbdeeddccdaabbabbdedaaabcdadbdabeacbeadbaddcbaacdbabcccbaceedbcccedbeecbccaecadccbdbdccbcbaacccbddcccbaedbacdbcaccdcaadcbaebebcceabbdcdeaabdbabadeaaaaedbdbcebcbddebccacacddebecabccbbdcbecbaeedcdacdcbdbebbacddddaabaedabbaaabaddcdaadcccdeebcabacdadbaacdccbeceddeebbbdbaaaaabaeecccaebdeabddacbedededebdebabdbcbdcbadbeeceecdcdbbdcbdbeeebcdcabdeeacabdeaedebbcaacdadaecbccbededceceabdcabdeabbcdecdedadcaebaababeedcaacdbdacbccdbcece"; net_ex1 n = new net_ex1(); System.out.println(n.minCut(t1)); } }