Leetcode: 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.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]

Combine Longest Palindrome Substring with Word Break II. Use Longest Palindrome Substring to create a palindrome dictionary, and then use that dictionary to do Word Break II.

public class Solution {
    public ArrayList<ArrayList<String>> partition(String s) {
        ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
        if (s == null || s.length() == 0) {
            return res;
        }
        
        ArrayList<String> item = new ArrayList<String>();
        Set<String> dict = getDict(s);
        int maxLength = 0;
        for (String sub : dict) {
            maxLength = Math.max(maxLength, sub.length());
        }
        helperPartition(s, dict, res, item, maxLength, 0);
        return res;
    }
    
    private void helperPartition(String s, Set<String> dict, ArrayList<ArrayList<String>> res, 
        ArrayList<String> item, int maxLength, int pos) {
        if (pos == s.length()) {
            res.add(new ArrayList<String>(item));
            return;
        }
        
        for (int i = 1; i <= maxLength && i + pos <= s.length(); i++) {
            String word = s.substring(pos, pos + i);
            if (dict.contains(word)) {
                item.add(word);
                helperPartition(s, dict, res, item, maxLength, pos + i);
                item.remove(item.size() - 1);
            }
        }
    }
    
    private Set<String> getDict(String s) {
        Set<String> res = new HashSet<String>();
        for (int i = 0; i < 2 * s.length() - 1; i++) {
            int start = i / 2;
            int end = i / 2;
            if (i % 2 == 1) {
                end++;
            }
            while (start>= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) {
                res.add(s.substring(start, end + 1));
                start--;
                end++;
            }
        }
        
        return res;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值