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"] ]
题解:以aab来说明算法:
所以这一个典型的递归算法:首先判断s(0,i)是否是回文,如果是,将s(0,i)暂存到result列表中,再递归的判断s(i+1,s.length)是否是回文,递归返回时,将s(0,i)从result中拿出来,继续循环判断s(0,i+1)是否回文......在递归的过程中,如果传递给递归函数的s是空串,说明找到了一中分割方法,并且存放在result列表中,那么此时就把result放到最终的答案列表answer中。
代码如下:
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 }
【leetcode刷题笔记】Palindrome Partitioning,布布扣,bubuko.com
【leetcode刷题笔记】Palindrome Partitioning
原文:http://www.cnblogs.com/sunshineatnoon/p/3854751.html