Give a string, and then cut several times at arbitrary positions to ensure that each substring after cutting is a palindrome string. Output all cutting results that meet the requirements.
aabb First consider cutting at the first position, a | abb In this way, we only need to know all the results of abb, and then add a to the head of all results All results of abb are [a b b] [a bb] Add a to the head of each result, which is [a a b b] [a a bb]
aabb Consider cutting at the second position again, aa | bb In this way, we only need to know all the results of bb, and then add aa to the head of all the results All results of bb are [b b] [bb] Add aa to the head of each result, which is [aa b b] [aa bb]
aabb Then consider cutting at the third position, aab | b Because aab is not a palindrome string, skip directly
aabb Then consider cutting at the fourth position, aabb | Because aabb is not a palindrome string, skip directly
In the end all the results are all added up [a a b b] [a a bb] [aa b b] [aa bb]
The intermediate process to get all the results of abb, aab, etc., and can be done with recursion. In the case of recursive exit point, all substrings of an empty string are just an empty list.
public List<List<String>> partition(String s) { return helper(s, 0); }
private List<List<String>> helper(String s, int start) { // exit recursive if (start == s.length()) { List<List<String>> temp = new ArrayList<>(); temp.add(new ArrayList<>());
return temp; }
List<List<String>> result = new ArrayList<>(); for (int i = start; i < s.length(); i++) { // only continue if left part is palindrome if (isPalindrome(s.substring(start, i + 1))) { String left = s.substring(start, i + 1);
for (List<String> temp : helper(s, i + 1)) { // append left part in beginning temp.add(0, left); result.add(temp); } } }
return result; }
// helper method to check whether a string is palindrome privatebooleanisPalindrome(String s){ int i = 0; int j = s.length() - 1;
while (i < j) { if (s.charAt(i) != s.charAt(j)) { returnfalse; }