Given a stringS, PartitionSSuch that every substring of the partition is a palindrome.
Return all possible palindrome partitioningS.
For example, givenS="aab"
,
Return
[ ["aa","b"], ["a","a","b"] ]
Question: Use Aab to describe the algorithm:
- Check whether the first character is a and whether it is a background. If it is a background, recursively judge whether the remaining AB is a background;
- Check the first two characters AA to determine whether to return the text. If the result is a return text, recursively judge whether the remaining B is returned;
- Check the first three characters of AAB to determine whether it is a text return. If it is not a text return.
- The loop ends.
So this typical recursive algorithm: first judge whether s (0, I) is a return. If so, save S (0, I) to the result list, then recursively judge S (I + 1, S. length) indicates whether it is a return. When returning recursively, take S (0, I) out of the result and continue to judge whether s (0, I + 1) is a return ...... in the recursive process, if the s passed to the recursive function is an empty string, it indicates that a segmentation method is found and stored in the result list, then, the result is placed in the final answer list answer.
The Code is as follows:
1 public class Solution { 2 private boolean isPar(String s){ 3 int begin = 0; 4 int end = s.length() - 1; 5 6 while(begin < end){ 7 if(s.charAt(begin) != s.charAt(end)) 8 return false; 9 10 begin++;11 end--;12 }13 14 return true;15 }16 public void partitionDfs(String s,List<String> result,List<List<String>> answer){17 if(s.length() == 0){18 List<String> temp = new ArrayList<String>(result);19 answer.add(temp);20 return;21 }22 23 int length = s.length();24 for(int i = 1;i <= length;i++){25 String sub = s.substring(0,i);26 if(isPar(sub)){27 result.add(sub);28 partitionDfs(s.substring(i), result, answer);29 result.remove(result.size()-1);30 }31 }32 33 }34 public List<List<String>> partition(String s) {35 List<List<String>> answer = new ArrayList<List<String>>();36 List<String> result = new ArrayList<String>();37 partitionDfs(s, result, answer);38 39 return answer;40 }41 }