Given a string s, partition s such that every substring of the partition are a palindrome.
Return all possible palindrome partitioning of S.
For example, given s = "AaB",
Return
[
["AA", "B"],
["A", "a", "B"]
]
Problem solving idea One:
The S into the left and right two parts, respectively, to find the partition on both sides, and then stick a piece, Java implementation is as follows:
static public list<list<string>> partition (String s) {set<list<string>> Set = new hashset< List<string>> (); if (Ispalindrome (s)) {list<string> alist = new arraylist<string> (); Alist.add (s) ; Set.add (alist);} for (int i = 1; i < s.length (); i++) {list<list<string>> left = partition (s.substring (0, i)); list<list<string>> right = partition (S.substring (i, S.length ())), and for (list<string> Aleft:left) for ( list<string> aright:right) {list<string> alist = new arraylist<string> (aLeft); Alist.addAll (ARight) ; Set.add (new arraylist<string> (alist));}} return new arraylist<list<string>> (set);} Static Boolean ispalindrome (String s) {int left = 0;int right = s.length ()-1;while (left < right) if (S.charat (left++ ) = S.charat (right--)) return False;return true;}
Results tle
Two ways to solve problems:
Modify the next idea, starting from the left, if the left side is palindrome, to the right of a partition, so that the results will not be repeated, so that you can AC, Java implementation is as follows:
static public list<list<string>> partition (String s) {arraylist<list<string>> List = new Arraylist<list<string>> (); if (Ispalindrome (s)) {list<string> alist = new Arraylist<string> () ; Alist.add (s); List.add (alist);} for (int i = 1; i < s.length (); i++) if (Ispalindrome (s.substring (0, i)) {list<string> aleft = new Arraylist<s Tring> (); Aleft.add (s.substring (0, i)); list<list<string>> right = partition (S.substring (i, S.length ())) and for (list<string> aright:right) { List<string> alist = new arraylist<string> (aleft); Alist.addall (aright); List.add (New ArrayList<String > (alist));}} return list;} Static Boolean ispalindrome (String s) {int left = 0;int right = s.length ()-1;while (left < right) if (S.charat (left++) ! = S.charat (right--)) return False;return true;}
Java for Leetcode 131 palindrome Partitioning