[LeetCode#267] Palindrome Permutation II

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

转载于:https://www.cnblogs.com/airwindow/p/4806012.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值