Palindrome Partitioning

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"]
]
public class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> result = new ArrayList<>();
        if (s == null || s.length() == 0) {
            return result;
        }
        
        partitionHelper(s, result, new ArrayList<String>(), 0);
        
        return result;
    }
    
    void partitionHelper(String s, List<List<String>> result, List<String> list, 
        int start) {
        if (s.length() == start) {
            result.add(new ArrayList<String>(list));
            return;
        }
        
        for (int i = start; i < s.length(); i++) {
            String str = s.substring(start, i + 1);
            
            if (isPalindrome(str)) {
                list.add(str);
                
                partitionHelper(s, result, list, i + 1);
                list.remove(list.size() - 1);
            }
        }
    }
    
    boolean isPalindrome(String s) {
        int i = 0, j = s.length() - 1;
        
        while (i < j) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            } else {
                i++;
                j--;
            }
        }
        
        return true;
    }
}

Hope this helps,
Michael

DigitalOcean Referral Badge