lintcode-分割回文串-136
阿新 • • 發佈:2019-01-03
給定一個字串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; };