[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;
    }
    
}

 

posted @ 2020-02-17 11:47  xuan_abc  阅读(124)  评论(0编辑  收藏  举报