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

[LeetCode]Palindrome Permutation II

时间:2015-11-30 08:29:03      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

递归做法

public class Solution {
    List<String> result = new ArrayList<String>();
    public List<String> generatePalindromes(String s) {
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        for (int i = 0; i < s.length(); i++) {
            int tmp = map.containsKey(s.charAt(i)) ? map.get(s.charAt(i)) : 0;
            map.put(s.charAt(i), tmp + 1);
        }
        Iterator<Character> it = map.keySet().iterator();
        char singal = ‘0‘;
        while (it.hasNext()) {
            char tmp = it.next();
            if (map.get(tmp) % 2 != 0) {
                if (singal != ‘0‘) {
                    return result;
                }
                singal = tmp;
            }
        }
        if (singal == ‘0‘) {
            helper(map, "");
        } else {
            map.put(singal, map.get(singal) - 1);
            helper(map, String.valueOf(singal));
        }
        return result;
    }
    public void helper(HashMap<Character, Integer> map, String str) {
        Iterator<Character> it = map.keySet().iterator();
        boolean flg = true;
        while (it.hasNext()) {
            char tmp = it.next();
            int count = map.get(tmp);
            if (count == 0) {
                continue;
            }
            flg = false;
            if (str.length() > 1 && tmp == str.charAt(0)) {
                continue;
            }
            for (int i = 0; i < count / 2; i++) {
                HashMap<Character, Integer> new_map = new HashMap<Character, Integer>(map);
                new_map.put(tmp, new_map.get(tmp) - (i + 1) * 2);
                String s = "";
                for (int j = 0; j < i + 1; j++) {
                    s += tmp;
                }
                helper(new_map, s + str + s);
            }
        }
        if (flg) {
            result.add(str);
        }
    }
}

 

[LeetCode]Palindrome Permutation II

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/5006209.html

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