131. Palindrome Partitioning

Description

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

Solution

DFS

class Solution {
    public List> partition(String s) {
        List> partitions = new LinkedList<>();
        if (s == null) {
            return partitions;
        }
        
        partitionRecur(s, 0, new LinkedList<>(), partitions);
        return partitions;
    }
    
    public void partitionRecur(String s, int i, List partition
                               , List> partitions) {
        if (i == s.length()) {
            partitions.add(new LinkedList<>(partition));
            return;
        }
        
        for (int j = i; j < s.length(); ++j) {
            if (isPalindrome(s, i, j)) {
                partition.add(s.substring(i, j + 1));
                partitionRecur(s, j + 1, partition, partitions);
                partition.remove(partition.size() - 1);
            }
        }
    }

    public boolean isPalindrome(String s, int i, int j) {
        while (i < j && s.charAt(i) == s.charAt(j)) {
            ++i;
            --j;
        }
        
        return i >= j;
    }
}

DP, time O(n^2), space?

不喜欢这个写法,好麻烦。

class Solution {
    public List> partition(String s) {
        List> partitions = new LinkedList<>();
        if (s == null || s.isEmpty()) {
            return partitions;
        }
        
        Map>> indexToPartition = new HashMap<>();
        int[][] isPalindrome = new int[s.length()][s.length()];
        
        for (int i = 0; i < s.length(); ++i) {
            List> partition = new LinkedList<>();
            
            for (int j = i; j >= 0; --j) {
                if (s.charAt(j) == s.charAt(i) && 
                    (i - j < 2 || isPalindrome[j + 1][i - 1] == 1)) {
                    isPalindrome[j][i] = 1;
                    String palindrome = s.substring(j, i + 1);
                    
                    if (j == 0) {
                        List newList = new LinkedList<>();
                        newList.add(palindrome);
                        partition.add(newList);
                        continue;
                    }
                    
                    for (List list : indexToPartition.get(j - 1)) {
                        List newList = new LinkedList<>(list);
                        newList.add(palindrome);    // append palindrome
                        partition.add(newList);
                    }
                } else {
                    isPalindrome[j][i] = -1;
                }
            }
            
            indexToPartition.put(i, partition);
        }
        
        return indexToPartition.get(s.length() - 1);
    }
}

你可能感兴趣的:(131. Palindrome Partitioning)