
Desicription
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
1 2 3 4 5 6
|
Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ]
|
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
class { private: void dfs(int index, string& s, vector<string>& path, vector<vector<string>>& res) { if(index == s.size()) { res.push_back(path); return ; } for(int i = index; s[i]; i++) { if(isPalindrome(s, index, i)) { path.push_back(s.substr(index, i - index + 1)); dfs(i + 1, s, path, res); path.pop_back(); } } } bool isPalindrome(string& s, int left, int right) { while(left <= right) if(s[left++] != s[right--]) return false; return true; } public: vector<vector<string>> partition(string s) { vector<vector<string>> res; vector<string> path; dfs(0, s, path, res); return res; } };
|
近期评论