题目描述:
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);
}
}
};
字符串回文排列算法解析
本文深入探讨了一种用于寻找字符串所有回文排列的算法。通过实例演示了如何使用哈希映射和递归调用来生成不重复的回文字符串组合,特别关注于处理奇数个字符的情况。
885

被折叠的 条评论
为什么被折叠?



