[LeetCode 131] Palindrome Partitioning (medium)

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

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

Solution

It reaches the ith charater when partitioning:

  • Try everyj (j >= i)to check if the substring between theith and jth character is palindrome
  • If it’s palindrome, partition the substring after the jth character

例如,Input: "aab"

  1. 首先访问第一个a,Try everyj (j >= i)to check if the substring between theith and jth character is palindrome ==》 从index 0切开,首先判断,a是不是回文,如果是,则将其加入substringEntry,然后继续迭代处理index 0 以后substring ab
  2. 再try next j, 从index 1 切开,判断aa是不是回文,如果是,则将其加入substringEntry,然后继续迭代处理index 以后substringb`.
  3. Base case: current index == str.length (), 表示整个String已经被访问了一遍,将substringsEntry加入结果并返回。
class Solution {
    public List> partition(String s) {
        List> result = new ArrayList<> ();
        if (s.length () == 0 || s == null) {
            return result;
        }
        
        List subStringsEntry = new ArrayList<> ();
        
        partitionHelper (s, result, subStringsEntry, 0);
        
        return result;
    }
    
    private void partitionHelper (String str, List> result, List subStringsEntry, int start) {
        if (start == str.length ()) {
            result.add (new ArrayList<> (subStringsEntry));
            return;
        }
        
        // solution:
        // It reaches the ith charater when partitioning:
        // Try every j (j >= i) to check if the substring between the ith and jth character is palindrome
        // If it’s palindrome, partition the substring after the jth character
        
        for (int i = start; i < str.length (); i ++) {
            if (isPalindrome (str, start, i)) {
                subStringsEntry.add (str.substring(start, i + 1));
                
                partitionHelper (str, result, subStringsEntry, i + 1);
                subStringsEntry.remove (subStringsEntry.size() - 1);
            }
        }
    }
    
    private boolean isPalindrome (String str, int start, int end) {
        while (start < end) {
            if (str.charAt (start) != str.charAt (end)) {
                return false;
            }
            
            start ++;
            end --;
        }
        
        return true;
    }
}

你可能感兴趣的:([LeetCode 131] Palindrome Partitioning (medium))