zoukankan      html  css  js  c++  java
  • 131. Palindrome Partitioning 131.回文分区

    Given a string s, partition s such that every substring of the partition is a palindrome.

    Return all possible palindrome partitioning of s.

    Example:

    Input: "aab"
    Output:
    [
      ["aa","b"],
      ["a","a","b"]
    ]

    1 图示:双重循环的逻辑
    ajhdfhjfbhjrfbkef
      s i i+1 i+2...
        s i i+1 i+2...
    
    
    

    2 递归的思想:start变成i+1, i相应往后。start的变化是在递归里完成的。

    for(int i=start;i<s.length();i++){ 从变量循环
                    if(isPal(s,start,i)){
                        list.add(s.substring(start,i+1)); 
                        dfs(s,i+1,list,res); start变成i+1, i相应往后。start的变化是在递归里完成的。
                        list.remove(list.size()-1);
                    }
                }

    3 不知道isPalindrome(String s, int low, int high)要这样写,更方便

    4 length()要加括号

    class Solution {
        public List<List<String>> partition(String s) {
            //cc
            List<String> temp = new ArrayList<>();
            List<List<String>> result = new ArrayList<>();
            
            if (s == null) return null;
            if (s.length() == 0) return result;
            
            dfs(s, 0, temp, result);
            
            return result;
        }
        
        public void dfs(String s, int start, List<String> temp, List<List<String>> result) {
            if (start == s.length()) {
                result.add(new ArrayList(temp));
            }else {
                for (int i = start; i < s.length(); i++) {
                    if (isPalindrome(s, start, i)) {
                        temp.add(s.substring(start, i + 1));
                        dfs(s, i + 1, temp, result);
                        temp.remove(temp.size() - 1);
                    }
                }
            }
        }
        
        //isPalindrome
        public boolean isPalindrome(String s, int start, int end) {
            while (start < end) {
                if (s.charAt(start++) != s.charAt(end--))
                    return false;
            }
            return true;
        }
    }
    View Code


  • 相关阅读:
    vue项目中npm安装sass,less,stylus
    jQueryniceScroll滚动条错位问题
    基于github发布 个人网站/博客
    【转载】预处器的对比——Sass、LESS和Stylus
    元素,布局方式,BFC和清除浮动
    使用git向github中添加项目并更新(备忘录)
    nginx 之 grok 过滤
    gitlab 同步小脚本
    svn同步小脚本
    使用pip命令自动生成项目安装依赖清单
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13222322.html
Copyright © 2011-2022 走看看