您的位置:首页 > 其它

leetcode Palindrome Partitioning II

2014-09-09 21:10 381 查看


Palindrome Partitioning II

Total Accepted: 14865 Total
Submissions: 82333My Submissions

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.

Have you been asked this question in an interview?
Yes

Discuss

这道题目,对于O(n^2)求出所有的回文字串,必须用dp的方法。参考我前一篇文章 /article/10927820.html

然后这篇文章,求出最小划分,需要用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];
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: