Code is not that clean....
First find out how many odd number of characters.... if there are more than one, it can't form palindrome.
If there is only one odd number character, if the odd number is one, we only need to permute the even/2 number characters.
if the odd number is more than one, we need to permute (odd + 1) / 2 characters + the even/2 number characters.
Suppose we have "aabb"---> it can form permutation for sure, we only need to permute ab, and then append the reverse of them to form the permutation.
Suppose we have "aabbc" --> we do the same as above, but append c in the middle.
Suppose we have "aabbccc" --> we need to perform permutation for abcc --> append the other c in the middle.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
/*
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 [];
*/
void permuteString(string tmp, string path, vector<string>& res) {
if(tmp == "") {res.push_back(path); return;}
for(int i = 0; i < tmp.size(); ++i) {
if(i > 0 && (tmp[i] == tmp[i-1])) continue;
string remaining = tmp.substr(0, i) + tmp.substr(i + 1);
permuteString(remaining, path + tmp[i], res);
}
}
vector<string> palindromePermutation(string s) {
vector<string> res;
string path = "";
vector<int> charMap(26, 0);
for(int i = 0; i < s.size(); ++i) {
charMap[s[i] - 'a']++;
}
int oddCount = 0;
for(int i = 0; i < 26; ++i) {
if(charMap[i] % 2) {
oddCount++;
if(oddCount > 1) return {};
}
}
string tmp = "";
for(int i = 0; i < 26; ++i) {
if((charMap[i] % 2 != 0) && (charMap[i] > 1)) {
for(int j = 0; j < (charMap[i] + 1) / 2; ++j) tmp += (i + 'a');
} else if(charMap[i] > 0){
for(int j = 0; j < charMap[i] / 2; ++j) tmp += (i + 'a');
}
}
permuteString(tmp, path, res);
string oddChar = "";
for(int i = 0; i < 26; ++i) {
if(charMap[i] % 2 != 0) oddChar += (i + 'a');
}
vector<string> result;
for(int i = 0; i < res.size(); ++i) {
string a = res[i];
reverse(a.begin(), a.end());
string tmp = res[i] + oddChar + a;
result.push_back(tmp);
}
return result;
}
int main(void) {
vector<string> res = palindromePermutation("aabbccc");
for(int i = 0; i< res.size(); ++i) cout << res[i] << endl;
}
本文介绍了一种算法,用于找出所有可能的回文排列,并确保没有重复。通过统计字符出现次数来判断是否能形成回文串,并使用递归进行排列。
896

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



