[LeetCode] 131. 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"]
]

Thought process:
Search for all the subsets of string partitions. For every partition, check if it's a palindrome.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> partitions = new ArrayList<>();
        List<String> partition = new ArrayList<>();
        partition(s, 0, partition, partitions);
        
        return partitions;
    }
    
    private void partition(String s, int start, List<String> partition, List<List<String>> partitions) {
        if (start == s.length()) {
            partitions.add(new ArrayList<>(partition));
            return;
        }
        
        for (int i = start; i < s.length(); i++) {
            String substring = s.substring(start, i + 1);
            
            if (isPalindrome(substring)) {
                partition.add(substring);
                partition(s, i + 1, partition, partitions);
                partition.remove(partition.size() - 1);
            }
        }
    }
    
    private boolean isPalindrome(String s) {
        int start = 0;
        int end = s.length() - 1;
        
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        
        return true;
    }
}

Time complexity: O(n! * n^2).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula