[LeetCode267]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:

    If a palindromic permutation exists, we just need to generate the first half of the string.
    To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation.
Hide Tags Backtracking
Hide Similar Problems (M) Next Permutation (M) Permutations II (E) Palindrome Permutation

根据提示,我们只要产生一半permutation, 最后把每个permutation reverse一下append它自己之后就可以了。如果有odd char 注意加在中间。比如对于aabbccd,我们先找出d是个odd frequency的char,然后找出一半的string应该是abc,对于abc有的permutation 是: abc, acb, bac, bca, cab, cba. 对于每个permutation, 先加上odd frequency char(if it has) 再reverse自己加到后面就有了palindrome permutation. 比如:abcdcba等。

找odd frequency char的方法跟I一样。
找permutation的方法和permutation II一样,注意可能有duplicate char。

class Solution {
public:
    vector<string> generatePalindromes(string s) {
        vector<string> res;
        int odd = 0, singleIdx = -1;
        int mp[256] = {0};
        for(char c : s){
            if(++mp[c]%2 == 1) ++odd;
            else --odd;
        }
        // no palindrom permutation;
        if(odd > 1) return res;
        string half = "";
        //generate half string.
        for(int i = 0; i<256; ++i){
            half.append(mp[i]/2, char(i));
            if(mp[i]%2==1) singleIdx = i;
        }

        vector<string> permutations;
        //get half permutation;
        getPermutation(half, 0, permutations);
        //reverse each of them and append it to the tail of p.
        for(auto p : permutations){
            string tmp = p;
            reverse(tmp.begin(), tmp.end());
            if(singleIdx >= 0 ) p += char(singleIdx);// there is a signle char add it to the middle;
            res.push_back(p + tmp);
        }
        return res;
    }
    void getPermutation(string halfStr, int pos, vector<string>& strs){
        if(pos == halfStr.size()){
            strs.push_back(halfStr);
            return;
        }
        for(int i = pos; i<halfStr.size(); ++i){
            if(i!=pos && halfStr[i] == halfStr[pos]) continue;
            swap(halfStr[i], halfStr[pos]);
            getPermutation(halfStr, pos+1, strs);
        }
    }
};

小note:
把int 转成char 直接用char(i)即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值