您的位置:首页 > 其它

LeetCode Palindrome Partitioning II

2013-09-30 19:13 411 查看
Palindrome Partitioning IIMar
113297
/ 47208

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 {
private:
void findpalindrome(const string &s, bool **flag, int cur, int len,
vector< vector<string> >& res, bool *sign) {
if(cur >= len - 1) {
vector<string> tmp;
for(int i = 0, prei = 0; i < len; i++) {
if(sign[i] == true) {
tmp.push_back(s.substr(prei, i - prei + 1));
prei = i + 1;
}
}
res.push_back(tmp);
}
for(int i = cur + 1; i < len; ++i) {
if(flag[cur+1][i]) {
sign[i] = true;
findpalindrome(s, flag,  i, len, res, sign);
sign[i] = false;
}
}
}
public:
vector<vector<string>> partition(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<string> > res;
if(s == "")
return res;

int len = s.size();
bool **flag = new bool*[len];
for(int i = 0; i < len; ++i)  {
flag[i] = new bool[len];
fill(flag[i], flag[i] + len, false);
}
//fill(&flag[0][0], &flag[len][len], false);
/*
for(int i = 0; i < len; ++i)  {
for(int j = i; j < len; ++j) {
if(s[j] == s[i] && (j >= i || true == flag[i+1][j-1]))
flag[i][j] = true;
}
}*/
for(int step = 0; step < len; ++step) {
for(int i = 0; i < len - step; ++i) {
int j = i + step;
if(s[i] == s[j] && (i == j || i + 1 == j ||  true == flag[i+1][j-1]))
flag[i][j] = true;
}
}

bool *sign = new bool[len];
fill(sign, sign + len, 0);
findpalindrome(s, flag, -1, len, res, sign);
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: