您的位置:首页 > 其它

Leetcode:Palindrome Partitioning II

2014-07-23 18:26 337 查看
Description:

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.

分析:求字符串的最小切,简单来看 对每一个新字符,往前找到它组成的所有回文,保留最小值,遍历整个字符串,即可以得到最小切得结果。

这里往前找,会将字符串分成两部分,带当前字符的回文部分,和前面的字符串部分。这样就会带来大量的重复子问题,当然考虑是动态规划来做。

动态规划的递归式是: F(x) = min{F(j)+1} for all j,s.t string [j+1,x] is a palindrome.

这里还有一个技巧需要注意,因为此时我们就需要判断一个字符串是否是回文串,判断方法也应该用动态规划来做,否则会超时。 判断回文的动归

比较简单,递归式是 B[i][j] = (s[i]==s[j]) && B[i+1][j-1]

然后是代码:

class Solution {
public:
int minCut(string s) {
//初步感觉是动态规划来做,每次多进来一个字符,去看他跟之前元素的最长匹配串,并
//和他单独割开比较,取最小值,记录下来。
if(s.size()<2) return 0;
int sz = s.size();
int *record = new int[s.size()];
vector<vector<bool> > palinrec(sz,vector<bool>(sz,false));

memset(record,0,sizeof(record));

for(int i=1;i<s.size();i++)
{
int index;
for(int j=i;j>=0;--j)
{
if(tellpalin(s,j,i,palinrec))
{
index = j;
if(index==i)
{
record[i] = record[i-1]+1;
}
else if(index>0)
{
record[i] = min(record[index - 1] + 1, record[i]);
}
else{
record[i]=0;
}
}
}
}
return record[s.size()-1];

}
bool tellpalin(string &s, int left,int right,vector<vector<bool> >&palinrec)
{
bool flag = true;
if(s[left]!=s[right])
{
palinrec[left][right]=0;
return false;
}
if( (left+1) < (right-1))
{
flag = palinrec[left+1][right-1];
}
palinrec[left][right] = flag;
return flag;
}

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