Last active
December 16, 2015 20:49
-
-
Save weidagang/5495278 to your computer and use it in GitHub Desktop.
Parlindrome Partitioning. Given a string s, partition s such that every substring of the partition is a palindrome.Return all possible palindrome partitioning of s.For example, given s = "aab", Return [ ["aa","b"], ["a","a","b"] ]. http://leetcode.com/onlinejudge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| vector<vector<string>> partition(string s) { | |
| vector<vector<string>> results; | |
| if (0 == s.size()) { | |
| return results; | |
| } | |
| for (int i = 0; i < s.size(); ++i) { | |
| string head = s.substr(0, i + 1); | |
| if (isPalindrome(head)) { | |
| vector<vector<string>> tails = partition(s.substr(i + 1)); | |
| if (tails.size() > 0) { | |
| for (int j = 0; j < tails.size(); j++) { | |
| tails[j].insert(tails[j].begin(), head); | |
| results.push_back(tails[j]); | |
| } | |
| } | |
| else { | |
| vector<string> result; | |
| result.push_back(head); | |
| results.push_back(result); | |
| } | |
| } | |
| } | |
| } | |
| private: | |
| bool isPalindrome(const string& a) { | |
| for (int i = 0; i < a.size() / 2; ++i) { | |
| if (a[i] != a[a.size() - 1 - i]) { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment