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.
这道题目,对于O(n^2)求出所有的回文字串,必须用dp的方法。参考我前一篇文章 http://blog.csdn.net/nan327347465/article/details/39157263
然后这篇文章,求出最小划分,需要用dp的思想,不然会超时。
/**
* Use the dp thought, the dp store the infomation of minCut for dp[0]=0, for the one character is palindrome partitioning, and for
* dp[1] if s[0]~s[1] is palindrome then the dp[1] is zero, otherwise dp[1] = dp[0]+1; For dp[2] if s[0]~s[2] is palindrome then the
* dp[2] = 0. However the thing is not that easy. If s[0]~s[2] is not palindrome, you should set dp[2] be min(dp[0]+1,dp[1]+1)
* respectively the condition is s[1]~s[2] is palindrome or s[2]~s[2] is palindrome.
* For the general dp function
* dp[i] = 0 if(s[0]~s[i] is palindrome)
* or min (dp[j]+1) 0<j<i if(s[j+1]~s[i] is palindrome)
*
*/
class Solution {
public:
int minCut(string s) {
int i,j,len = s.size();
vector<vector<bool> > palin(len,vector<bool>(len,false));
vector<int> dp (len,0);
// learn the initialization of a palin system.
for(i=0;i<len;i++)
{
palin[i][i] = true;
if(i<len-1&&s[i]==s[i+1])
{
palin[i][i+1] = true;
}
}
for(i=2;i<len;i++)
{
for(j=0;j+i<len;j++)
{
if(s[j]==s[j+i]&&palin[j+1][j+i-1])
{
palin[j][j+i] = true;
}
}
}
//来一个双重循环,考虑到其有可能在中间某部分是回文串,所以还要从前向后计算。
for(i=0;i<len;i++)
{
if(palin[0][i])
{
dp[i] = 0;
}else
{
int tmp = 99999999;
for(j=0;j<i;j++)
{
if(palin[j+1][i] && tmp>(dp[j]+1))
{
tmp = dp[j]+1;
}
}
dp[i] = tmp;
}
}
return dp[len-1];
}
};