[LeetCode] 064: Palindrome Partition

来源:互联网 发布:js点击按钮让日期增加 编辑:程序博客网 时间:2024/06/08 02:54
[Problem]

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

  [    ["aa","b"],    ["a","a","b"]  ]
[Solution]
class Solution {
public:
/**
* is string s a palindrome string
*/
bool isPalindrome(string s){
if(s.size() == 0)return true;
int i = 0, j = s.size()-1;
while(i < j){
if(s[i] != s[j]){
return false;
}
i++;
j--;
}
return true;
}
/**
* partition
*/
vector<vector<string> > partition(string s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<string> > res;

// less than 2 characters
if(s.size() <= 1){
vector<string> row;
row.push_back(s);
res.push_back(row);
}
else{
// partition
for(int i = 1; i <= s.size(); ++i){
string head = s.substr(0, i);
if(!isPalindrome(head))continue;

// end of partition
if(i == s.size()){
vector<string> row;
row.push_back(head);
res.push_back(row);
}
else{
vector<vector<string> > nextRes = partition(s.substr(i, s.size()-i));
for(int j = 0; j < nextRes.size(); ++j){
nextRes[j].insert(nextRes[j].begin(), head);
res.push_back(nextRes[j]);
}
}
}
}
return res;
}
};
说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击