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"] ]
[Analysis]
最简单的方法,直接深搜。更好一点的方法,用mark[i][j]记录s[i:j]是不是回文,然后再深搜。
[Solution]
class Solution {
public:
// is the string a palindrome
bool isPalindrome(string s){
// string with one letter
if(s.length() <= 1){
return true;
}
// check
int i = 0, j = s.length() - 1;
while(i <= j){
if(s[i] != s[j]){
return false;
}
i++;
j--;
}
return true;
}
// partition
vector<vector<string> > partition(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<string> > res;
// empty string
if(s.length() == 0){
return res;
}
// string with one letter
else if(s.length() == 1){
vector<string> tmp;
tmp.push_back(s);
res.push_back(tmp);
}
// DFS
else{
// the length of the first part could be range from 0 to s.length()
for(int i = 1; i <= s.length(); ++i){
// get the first part
string head = s.substr(0, i);
// the first part is not a palindrome, continue
if(!isPalindrome(head))continue;
if(i == s.length()){
vector<string> tmp;
tmp.push_back(head);
res.push_back(tmp);
}
// generate the remained parts
else{
vector<vector<string> > r = partition(s.substr(i, s.length() - i));
for(int j = 0; j < r.size(); ++j){
r[j].insert(r[j].begin(), head);
res.push_back(r[j]);
}
}
}
}
return res;
}
};
说明:版权所有,转载请注明出处。 Coder007的博客