Leetcode Palindrome Permutation I & II

来源:互联网 发布:js获取所有兄弟节点 编辑:程序博客网 时间:2024/05/16 06:55

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"]]
给一个string, 返回所有的回文。


    public List<List<String>> partition(String s) {        List<List<String>> list = new ArrayList<>();        backtrack(list, new ArrayList<String>(), s, 0);        return list;    }        private void backtrack(List<List<String>> list, List<String> temp, String s, int start) {        if (start == s.length()) list.add(new ArrayList<String>(temp));        else {            for (int i = start; i < s.length(); i++) {                if (isPalindrome(s, start, i)) {                    temp.add(s.substring(start, i + 1));                    backtrack(list, temp, s, i + 1); i+1 避免重复                    temp.remove(temp.size() - 1);                }            }        }    }        private boolean isPalindrome(String s, int low, int high) {        while (low < high) {            if (s.charAt(low++) != s.charAt(high--)) return false;        }        return true;    }

Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.

For example:

Given s = "aabb", return ["abba", "baab"].

Given s = "abc", return [].

思路是:找单个出现的字母,如果多余两个则返回[]


    public List<String> generatePalindromes(String s) {        int[] map = new int[256];        for (char c : s.toCharArray()) map[c]++;        List<String> res = new ArrayList<>();        String mid = null;        for (int i = 0; i < map.length; i++) {            if (map[i] % 2 == 1) {                if (mid == null) mid = String.valueOf((char) i);                else return res;            }        }        helper(res, (mid == null) ? "" : mid, map, s.length());        return res;    }        private void helper(List<String> res, String tmp, int[] map, int len) {        if (tmp.length() == len) {            res.add(tmp);            return;        }        for (int i = 0; i < map.length; i++) {            if (map[i] >= 2) {                map[i] -= 2;                helper(res, (char) i + tmp + (char) i, map, len);                map[i] += 2;            }        }    }






原创粉丝点击