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

Palindrome Permutation II

时间:2017-10-22 10:54:56      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:mic   empty   cat   uil   nbsp   array   string   lis   logs   

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;
            }            
        }
        
    }

  

Palindrome Permutation II

标签:mic   empty   cat   uil   nbsp   array   string   lis   logs   

原文地址:http://www.cnblogs.com/apanda009/p/7707620.html

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