Palindrome Permutation II

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 [].

 

 private static List<String> test(String s) {
        
        List<String> ans = new ArrayList<>();
        if (s == null || s.length() == 0) {
            return ans;
        }
        int[] chs = new int[256];
        for (int i = 0; i < s.length(); i++) {
            chs[s.charAt(i)]++;
        }
        int count = 0;
        for (int i : chs) {
            if (i % 2 == 1) {
                count++;
            }
            if (count > 1) {
                return ans;
            }
        }
        String center = "";
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 256; i++) {
            if (chs[i] % 2 == 1) {
                center = (String.valueOf((char) i));
                chs[i]--;
                break;
            }            
        }
        dfs(ans, chs, center, s.length());
        return ans;        
    }
    private static void dfs(List<String> ans, int[] chs, String s, int len) {
        if (s.length() == len) {
            ans.add(s);
            return;
        }
        for (int i = 0; i < 256; i++) {
            if (chs[i] > 0) {
                chs[i] -= 2;
                dfs(ans, chs, ((char) i) + s + ((char) i), len);
                chs[i] += 2;
            }            
        }
        
    }

  

posted @ 2017-10-22 05:14  apanda009  阅读(125)  评论(0编辑  收藏  举报