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

[LeetCode#267] Palindrome Permutation II

时间:2015-09-14 06:58:58      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

Problem:

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

Analysis:

This problem is very easy, it shares the same idea with "Strobogrammatic Number". 
Use the rule you check a "Palindrome Permutation" to construct it!!! (two pointer!)

I have made one mistake in implementation. 
Forget that when "len == 1", the string must a pilindrome string!

Wrong part:
if (len <= 1) {
    return ret;
}

Errors:
Input:
"a"
Output:
[]
Expected:
["a"]

Solution:

public class Solution {
    public List<String> generatePalindromes(String s) {
        if (s == null)
            throw new IllegalArgumentException("s is null");
        List<String> ret = new ArrayList<String> ();
        int len = s.length();
        if (len == 0) {
            return ret;
        }
        HashMap<Character, Integer> map = new HashMap<Character, Integer> ();
        for (char c : s.toCharArray()) {
            if (map.containsKey(c))
                map.put(c, map.get(c)+1);
            else
                map.put(c, 1);
        }
        int odd_count = 0;
        char odd_char = ‘a‘;
        for (char c : map.keySet()) {
            if (map.get(c) % 2 == 1) {
                odd_count++;
                odd_char = c;
            }
        }
        if (odd_count >= 2)
            return ret;
        if (odd_count == 1) {
            searchPath(map, odd_char + "", len, ret);
        } else{
            searchPath(map, "", len, ret);
        }
        return ret;
    }
    
    
    private void searchPath(HashMap<Character, Integer> map, String cur, int target, List<String> ret) {
        String new_cur = cur;
        int len = new_cur.length();
        if (len == target) {
            ret.add(new_cur);
            return;
        }
        for (char c : map.keySet()) {
            if (map.get(c) >= 2) {
                new_cur = c + cur + c;
                map.put(c, map.get(c) - 2);
                searchPath(map, new_cur, target, ret);
                map.put(c, map.get(c) + 2);
            }
        }
    }
}

[LeetCode#267] Palindrome Permutation II

标签:

原文地址:http://www.cnblogs.com/airwindow/p/4806012.html

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