您的位置:首页 > 其它

lintcode-分割回文串-136

2015-10-14 21:48 302 查看
给定一个字符串s,将s分割成一些子串,使每个子串都是回文串。

返回s所有可能的回文串分割方案。

样例
给出 s = "aab",返回

[

["aa","b"],

["a","a","b"]

]

class Solution {
public:
vector<vector<string>> partition(string s) {
solve(s,s.length(),0);
return result;
}
private:
bool isPalindrome(const string &s){
int begin=0,end=s.length()-1;
while(begin<end){
if(s[begin]!=s[end])
return false;
    ++begin;
--end;
}
return true;
}
void solve(const string &s,int size,int pos){
if(pos==size){
result.push_back(path);
return ;
}
for(int i=pos;i<size;++i){
string prefix=s.substr(pos,i-pos+1);  //以s[pos]字符开头的所有前缀
if(!isPalindrome(prefix))             //不是回文串就继续找
continue;
path.push_back(prefix);               //加入path
solve(s,size,i+1);                    //从已经找到的回文串的下一个字符继续找
path.pop_back();                      //记得移除,path还要继续复用
}
}
vector<string> path;
vector<vector<string> > result;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: