leetcode第20题(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"]
  ]

思路:跟上面一题一样

代码:

import java.util.ArrayList;

public class Solution {
    public ArrayList<ArrayList> partition(String s) {
        ArrayList<ArrayList> lists = new ArrayList<>();
        ArrayList list = new ArrayList<>();
        partitionHelper(lists,list,s);
        return lists;
    }
    public static  void  partitionHelper(ArrayList<ArrayList> lists,ArrayList list,String s){
        if(s==null || s.length()==0){
            lists.add(new ArrayList(list));
            return;
        }
        int len=s.length();
        for(int i=0;i<=len;i++){
            String sub = s.substring(0,i);
            if(isPalindrome(sub)){
                list.add(sub);
                partitionHelper(lists,list,s.substring(i,len));
                list.remove(list.size()-1);
            }
        }
    }
    public static boolean isPalindrome(String s) {
        if (null == s || s.length() == 0) return false;
        int length = s.length();
        int middle = length / 2;
        for (int i = 0; i < middle;i++) {
            if (s.charAt(i) != s.charAt(length - 1 - i)) {
                return false;
            }
        }
        return true;
    }

}

你可能感兴趣的:(牛客网(leetcode))