码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 131. Palindrome Partitioning

时间:2020-02-17 12:18:03      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:new   div   code   inpu   public   remove   col   NPU   str   

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

标签:new   div   code   inpu   public   remove   col   NPU   str   

原文地址:https://www.cnblogs.com/xuanlu/p/12321016.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!