您的位置:首页 > 其它

132. Palindrome Partitioning II (String; DP)

2015-10-23 21:01 344 查看
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.

思路: 除了用flag[i][j]记录从i到j是否是Palindrome,还要用cut[i]存储到i位置位置最少的cut数

class Solution {
public:
int minCut(string s) {
int sLength = s.length();
vector<vector<bool>> flag(sLength,vector<bool>(sLength, false));
int cut[sLength];
cut[0]=0;

for (int i=1;i<sLength;i++)
{
cut[i]=1+cut[i-1];
for(int j=0;j<i;j++)
if(s[i]==s[j]&&(i-j<=2||flag[j+1][i-1]))
{
flag[j][i]=true;
if(j==0)
{
cut[i] = 0;
break;
}
else cut[i] = min(cut[i],1+cut[j-1]);
}
}
return cut[sLength-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: