Given a string s, partition s such that every substring of the partition is a palindrome.git
Return all possible palindrome partitioning of s.github
For example, given s = "aab"
,
Return測試
[ ["aa","b"], ["a","a","b"] ]
Subscribe to see which companies asked this question。this
class Solution { public: vector<vector<string>> partition(string s) { if (s.empty()) return vector<vector<string>>(); int len = s.length(); if (len == 1) return vector<vector<string>>(1, vector<string>(1, s)); else { vector<vector<string>> ret; int pos = 0; while (pos < len) { if (isPalindrome(s, 0, pos)) { if (pos == len - 1) { vector<string> tmp; tmp.push_back(s.substr(0, pos+1)); ret.push_back(tmp); } else{ /*獲取剩餘子串的全部迴文分隔結果*/ vector<vector<string>> subRet = partition(s.substr(pos + 1)); auto iter = subRet.begin(); while (iter != subRet.end()) { (*iter).insert((*iter).begin(), s.substr(0, pos + 1)); ret.push_back(*iter); ++iter; }//while }//else }//if ++pos; }//while return ret; } } /*判斷是否爲迴文串*/ bool isPalindrome(string str, int beg, int end) { if (beg <0 || beg > end || end >= str.length()) return false; while (beg < end) { if (str[beg++] != str[end--]) return false; }//while return true; } };GitHub測試程序源碼