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

Hint:

  1. If a palindromic permutation exists, we just need to generate the first half of the string.
  2. To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation.


感觉这类题做多了也就那么回事,只不过在dfs之前的条件需要仔细一些。

在判断是否是回文的时候考的绿naive了一点,用了int[] dict = new int[26], 结果发现输入不局限于a-z。还有就是统计奇数次的字符时,顺便需要更新可能作为中间点的字符。

代码:

public List<String> generatePalindromes(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        for(int i=0;i<s.length();i++){
            if(map.containsKey(s.charAt(i))){
                map.put(s.charAt(i), map.get(s.charAt(i))+1);
            }else{
                map.put(s.charAt(i), 1);
            }
        }
        int count = 0;
        char single = '*';
        List<Character> list = new ArrayList<>();
        for(Map.Entry<Character, Integer> entry: map.entrySet()){
            int value = entry.getValue();
            char ch = entry.getKey();
            if(value%2!= 0){
                count++;
                single = ch;
                if(value>1){
                    for(int i=0;i<(value-1)/2;i++){
                        list.add(ch);
                    }
                }
            }else{
                for(int i=0;i<value/2;i++){
                    list.add(ch);
                }
            }
        }
        if(count>1){
            return new ArrayList<>();
        }
        boolean visited[] = new boolean[list.size()];
        List<String> result = new ArrayList<>();
        //generate premutations
        String startStr = single == '*'?"":single+"";
        int totalLen = single == '*'?2*list.size():2*list.size()+1;
        generatePermutations(list, startStr, visited, result, totalLen);
        return result;
    }

    private void generatePermutations(List<Character> characters, String curStr, boolean[]visited, List<String> result, int totalLen){
        if(curStr.length() == totalLen){
            result.add(curStr);
            return;
        }
        for(int i=0;i<characters.size();i++){
            if(i!=0 && characters.get(i) == characters.get(i-1) && visited[i-1] == false) continue;
            if(visited[i] == false){
                visited[i] = true;
                char ch = (characters.get(i));
                generatePermutations(characters, ch+curStr+ch, visited, result, totalLen);
                visited[i] = false;
            }else{
                continue;
            }
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值