首页 > 代码库 > leetcode 131. Palindrome Partitioning----- java

leetcode 131. Palindrome Partitioning----- java

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

 

递归求解,没什么难度。

public class Solution {
    List list = new ArrayList<ArrayList<String>>();
    char[] word ;
    String ss;
    String[] result;

    public List<List<String>> partition(String s) {
        int len = s.length();
        if( len == 0)
            return list;
        if( len == 1 ){
            ArrayList<String> l1 = new ArrayList<String>();
            l1.add(s);
            list.add(l1);
            return list;
        }
        ss = s;
        word = s.toCharArray();
        result = new String[len];
        for( int i = 0;i < len;i++){
            if( isPalindrome(0,i) ){
                result[0] = s.substring(0,i+1);
                helper(i+1,1);
            }
        }
        return list;

    }

    public void helper(int start,int num){

        if( start == word.length ){
            ArrayList ll = new ArrayList<String>();
            for( int i = 0;i<num;i++)
                ll.add(result[i]);
            list.add(ll);
            return ;
        }



        for( int i = start; i < word.length;i++){
            if( isPalindrome(start,i) ){
                result[num] = ss.substring(start,i+1);
                helper(i+1,num+1);
            }
        }


    }

    public boolean isPalindrome(int start,int end){



        while( start < end ){
            if( word[start] == word[end] ){
                start++;
                end--;
            }else
                return false;
        }
        return true;



    }
}

 

 

 

 

leetcode 131. Palindrome Partitioning----- java