Leetcode: Palindrome Partitioning

来源:互联网 发布:mac pro 贴膜涂层脱落 编辑:程序博客网 时间:2024/05/01 15:34

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
原创粉丝点击