您的位置:首页 > 其它

LeetCode:Palindrome Partitioning II

2014-09-03 14:09 363 查看
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.

class Solution {
public:
int minCut(string s) {
s = '#' + s;
vector<int> result(s.size() + 1, INT_MAX);
result[0] = -1;
bool isPal[s.size()][s.size()];
for(int i = 0; i < s.size(); i++)
for(int j = 0; j < s.size(); j++)
{
isPal[i][j] = false;
}
for(int i = 1; i < s.size(); i++)
{
for(int j = 1; j <= i; j++)
{
if((i - j < 2 && s[i] == s[j]) || ((i - j >= 2) && isPal[j+1][i-1] && s[i] == s[j]))
{
isPal[j][i] = true;
if(j-1 < 0)
result[i] = 0;
else
result[i] = min(result[i], result[j-1] + 1);

}
}
}
return result[s.size() - 1];

}

};


Round 2:

class Solution {
public:
int minCut(string s) {
vector<int> cuts(s.size(), INT_MAX);
bool isPal[s.size()][s.size()];
cuts[0] = 0;
isPal[0][0] = true;
memset(isPal, 0, sizeof(isPal));
for(int i = 0; i < s.size(); i++)
{
for(int j = 0; j <= i; j++)
{
if((i-j > 2 && s[i] == s[j] && isPal[j+1][i-1]) || (i-j <= 2 && s[i] == s[j]))
{
isPal[j][i] = true;
if(j == 0)
cuts[i] = 0;
else
cuts[i] = std::min(cuts[i], cuts[j-1]+1);
}

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