LeetCode 267 - 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.

Example 1:

Input: "aabb"

Output: ["abba", "baab"]

Example 2:

Input: "abc"

Output: []
class Solution {
public:
    vector<string> generatePalindromes(string s) {
        unordered_map<char,int> hash;
        for(auto c:s) hash[c]++;
        vector<string> result;
        char center='\0';
        for(auto x:hash) // 确定奇数个的字符作为中心
        {
            if(x.second%2==1)
            {
                if(center!='\0') return result;
                else center=x.first;
            }
        }
        string cur;
        if(center!='\0') 
        {
            hash[center]--;
            if(hash[center]==0) hash.erase(center);
            cur.push_back(center);
        }
        permutate(cur,hash,result); // 将字符进行排列,两个相同字符可以放置于中心两端
        return result;
    }
    
    void permutate(string cur, unordered_map<char,int> hash, vector<string>& result)
    {
        if(hash.size()==0)
        {
            result.push_back(cur);
            return;
        }
        for(auto x:hash)
        {
            string next=x.first+cur+x.first;
            unordered_map<char,int> temp=hash;
            temp[x.first]-=2;
            if(temp[x.first]==0) temp.erase(x.first);
            permutate(next,temp,result);
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值