zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    oracle热备份与冷备份的对比
    oracle数据库备份
    shell 去除空行
    已有实例 Oracle 下新增实例(2)通过dbca克隆实例
    oracle启动,提示“LRM-00109: could not open parameter file”
    linux——使用fidsk对linux硬盘进行操作【转】
    前端——知识点
    hdu 3996 Gold Mine 最大权闭合子图
    hdu 3917 Road constructions 最大权闭合子图
    poj 2987 Firing 最大权闭合子图
  • 原文地址:https://www.cnblogs.com/echoht/p/3691956.html
Copyright © 2011-2022 走看看