题目描述:
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 generatePalindromes(string s) {
unordered_map hash;
for(auto c:s) hash[c]++;
vector 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 hash, vector& result)
{
if(hash.size()==0)
{
result.push_back(cur);
return;
}
for(auto x:hash)
{
string next=x.first+cur+x.first;
unordered_map temp=hash;
temp[x.first]-=2;
if(temp[x.first]==0) temp.erase(x.first);
permutate(next,temp,result);
}
}
};