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.
[Thoughts]
凡是求最优解的,一般都是走DP的路线。这一题也不例外。首先求dp函数,
定义函数
D[i,n] = 区间[i,n]之间最小的cut数,n为字符串长度
a b a b b b a b b a b a
i n
如果现在求[i,n]之间的最优解?应该是多少?简单看一看,至少有下面一个解
a b a b b b a b b a b a
i j j+1 n
此时 D[i,n] = min(D[i, j] + D[j+1,n]) i<=j <n。这是个二维的函数,实际写代码时维护比较麻烦。所以要转换成一维DP。如果每次,从i往右扫描,每找到一个回文就算一次DP的话,就可以转换为
D[i] = 区间[i,n]之间最小的cut数,n为字符串长度, 则,
D[i] = min(1+D[j+1] ) i<=j <n
有个转移函数之后,一个问题出现了,就是如何判断[i,j]是否是回文?每次都从i到j比较一遍?太浪费了,这里也是一个DP问题。
定义函数
P[i][j] = true if [i,j]为回文
那么
P[i][j] = str[i] == str[j] && P[i+1][j-1];
基于以上分析,实现如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int minCut(String s) { 3 int[] D=new int[s.length()+1]; 4 boolean[][] P=new boolean[s.length()][s.length()]; 5 6 // 将D[i] 初始化为 从 i 到 length 的最大cut 数,及cut为单个字符的cut数 7 for(int i=0;i<=s.length();i++){ 8 D[i]=s.length()-i-1; 9 } 10 11 for(int i=s.length()-1;i>=0;i--){ 12 for(int j=i;j<s.length();j++){ 13 // j-i < 2 两种情况: 1. i 和 j 相邻 2. i== j 14 if(s.charAt(i)==s.charAt(j)&&(j-i<2||P[i+1][j-1])){ 15 P[i][j]=true; 16 D[i]=Math.min(D[i],1+D[j+1]); 17 } 18 } 19 } 20 return D[0]; 21 } 22 }
Ref: http://fisherlei.blogspot.com/2013/03/leetcode-palindrome-partitioning-ii.html