链接:https://lintcode.com/problem/palindrome-partitioning/description
描述
给定一个字符串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; };