LeetCode题解: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”]
]

题意:给定一个字符串,分割字符串使得到的子串都是回文(palindrome)

解决思路:创建一个List<>数组,长度为字符串的长度,数组的索引表示字符串当前长度([0,index])。对该字符串[0,index]求回文子串,最终就能得到结果。

原因在于:长度小于字符串长度的子串的回文子串必然也是原字符串的回文子串。

public class Solution {
    public List<List<String>> partition(String s) {
        int len = s.length();
        List<List<String>>[] results = new List[len + 1];
        results[0] = new ArrayList<List<String>>();
        results[0].add(new ArrayList<String>());

        boolean[][] pairs = new boolean[len][len];
        for(int i = 0; i < len; i++){
            char c = s.charAt(i);
            results[i + 1] = new ArrayList<List<String>>();

            for(int j = 0; j <= i; j++){
                if(i == j){
                    pairs[j][i] = true;
                }else{
                    if(s.charAt(j) != c){
                        continue;
                    }

                    if(j == i - 1){
                        pairs[j][i] = true;
                    }else{
                        pairs[j][i] = pairs[j + 1][i - 1];
                    }
                }

                if(pairs[j][i]){
                    String str = s.substring(j, i + 1);
                    for(List<String> temp : results[j]){
                        List<String> result = new ArrayList<String>(temp);
                        result.add(str);
                        results[i + 1].add(result);
                    }
                }
            }
        }

        return results[len];
    }
}

你可能感兴趣的:(LeetCode)