[LeetCode267]Palindrome Permutation II

来源:互联网 发布:bu大都会学院知乎 编辑:程序博客网 时间:2024/05/22 13:59
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 BacktrackingHide 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
原创粉丝点击