[LC] 131. Palindrome Partitioning

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 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.

Example:

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

class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        List<String> list = new ArrayList<>();
        helper(res, list, 0, s);
        return res;
    }
    
    private void helper(List<List<String>> res, List<String> list, int level, String s) {
        if (level == s.length()) {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = level; i < s.length(); i++) {
            if (isPalin(s, level, i)) {
                list.add(s.substring(level, i + 1));
                helper(res, list, i + 1, s);
                list.remove(list.size() - 1);
            }
        }
    }
    
    private boolean isPalin(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start += 1;
            end -= 1;
        }
        return true;
    }
    
}

 

以上是关于[LC] 131. Palindrome Partitioning的主要内容,如果未能解决你的问题,请参考以下文章

131. Palindrome Partitioning

Leetcode 131:Palindrome Partitioning

[LC] 125. Valid Palindrome

131. Palindrome Partitioning

131. Palindrome Partitioning

131. Palindrome Partitioning