LeetCode OJ

这道题我采用的是递归算法解决的,时间复杂度虽然比较高,但是却可以被AC,期待看到更有效的方法。

我觉得求各种组合情况的问题一般采用递归算法。

下面是AC代码:

 1 /**
 2      * Given a string s, partition s such that every substring of the partition is a palindrome.
 3      * Return all possible palindrome partitioning of s.
 4      * @param s
 5      * @return
 6      */
 7     public ArrayList<ArrayList<String>> partition(String s){
 8         ArrayList<ArrayList<String>> global = new ArrayList<ArrayList<String>>();
 9         subPartition(global, null, 0,s);
10         return global;
11     }
12     /**
13      * 采用递归的方法,将规模较大的问题划分成规模较小的问题
14      * @param global
15      * @param curr
16      * @param start
17      * @param s
18      */
19     private void subPartition(ArrayList<ArrayList<String>> global, ArrayList<String> curr, int start, String s){
20         if(start == 0)
21             curr = new ArrayList<String>();
22         
23         if(start == s.length()-1){
24             curr.add(s.substring(start));
25             global.add(curr);
26             return;
27         }
28         
29         if(start>=s.length()){
30             global.add(curr);
31             return;
32         }
33             
34         for(int i = start;i<s.length();i++){
35             String sn = s.substring(start,i+1);
36             if(isPalindrome(sn)){
37                 ArrayList<String> nCurr = new ArrayList<String>();
38                 for(int k=0;k<curr.size();k++)
39                     nCurr.add(curr.get(k));
40                 nCurr.add(sn);
41                 subPartition(global,nCurr,i+1,s);
42             }
43         }    
44     }
45     /**
46      * 判断字符串是否是回文
47      * @param s
48      * @return
49      */
50     private boolean isPalindrome(String s){
51         int i=0;
52         int j=s.length()-1;
53         while(i<=j){
54             if(s.charAt(i++)!=s.charAt(j--))
55                 return false;
56         }
57         return true;
58     }
有问题可以和我联系,bettyting2010#163 dot com
原文地址:https://www.cnblogs.com/echoht/p/3691956.html