zoukankan      html  css  js  c++  java
  • Palindrome Partitioning

    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"]
    ]
    

    给定一个指针从字符串从前往后移动,从开头到该指针的字符串是回文,则递归剩下后面部分字符串。


    代码如下:

    class Solution {
        public List<List<String>> partition(String s) {
            List<List<String>> res=new ArrayList<List<String>>();
            if(s==null||s.length()==0) return res;
            helper(res,new ArrayList<String>(),s,0);
            return res;
        }
        public void helper(List<List<String>> res,List<String> list,String s,int index){
            if(index==s.length()){
                res.add(new ArrayList<String>(list));
                return ;
            }
            for(int i=index;i<s.length();i++){
                String sub=s.substring(index,i+1);
                if(isP(sub)){
                    list.add(sub);
                    helper(res,list,s,i+1);
                    list.remove(list.size()-1);
                }
            }
        }
        public boolean isP(String s){
            StringBuilder sb=new StringBuilder(s);
            return sb.reverse().toString().equals(s);
        }
    }
  • 相关阅读:
    Linux-文件目录管理
    20. 有效的括号
    242. 有效的字母异位词
    387. 字符串中的第一个唯一字符
    136. 只出现一次的数字
    14. 最长公共前缀
    268. 丢失的数字
    169. 多数元素
    26. 删除有序数组中的重复项
    283. 移动零
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8269010.html
Copyright © 2011-2022 走看看