Palindrome Partitioning LeetCode

 Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.


 


Example 1:


Input: s = "aab"

Output: [["a","a","b"],["aa","b"]]

Example 2:


Input: s = "a"

Output: [["a"]]



class Solution {
    public List<List<String>> partition(String s) {
         List<List<String>> result = new ArrayList<>();
        backtrack(s, 0, new ArrayList<>(), result);
        return result;
    }
     private void backtrack(String s, int startIndex, List<String> currentPartition, List<List<String>> allPartitions) {
        if (startIndex == s.length()) {
            allPartitions.add(new ArrayList<>(currentPartition));
            return;
        }

        for (int i = startIndex; i < s.length(); i++) {
            String substring = s.substring(startIndex, i + 1); // substring from startIndex to i

            if (isPalindrome(substring)) {
                currentPartition.add(substring); // choose
                backtrack(s, i + 1, currentPartition, allPartitions); // explore with remaining substring
                currentPartition.remove(currentPartition.size() - 1); // unchoose (backtrack)
            }
        }
    }

    private boolean isPalindrome(String str) {
        int left = 0, right = str.length() - 1;
        while (left < right) {
            if (str.charAt(left++) != str.charAt(right--)) return false;
        }
        return true;
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence