[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<List<String>> partition(String s) {
        List<List<String>> result = new ArrayList<> ();
        if (s.length () == 0 || s == null) {
            return result;
        }
        
        List<String> subStringsEntry = new ArrayList<> ();
        
        partitionHelper (s, result, subStringsEntry, 0);
        
        return result;
    }
    
    private void partitionHelper (String str, List<List<String>> result, List<String> 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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容