forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
64 lines (61 loc) · 1.25 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <cstdlib>
#include <iostream>
#include <map>
#include <queue>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> generatePalindromes(string s) {
vector<string> palindromes;
map<char, int> counts;
for (char c : s) {
counts[c]++;
}
int odd = 0;
char mid;
string half;
for (auto p : counts) {
if (p.second & 1) {
odd++, mid = p.first;
if (odd > 1) return palindromes;
}
half += string(p.second / 2, p.first);
}
palindromes = permutations(half);
for (string& p : palindromes) {
string t(p);
reverse(t.begin(), t.end());
if (odd) {
p += mid;
}
p += t;
}
return palindromes;
}
private:
vector<string> permutations(string& s) {
vector<string> perms;
string t(s);
do {
perms.push_back(s);
next_permutation(s.begin(), s.end());
} while (s != t);
return perms;
}
};
int main() {
Solution sol;
for (auto s : sol.generatePalindromes("code")) {
cout << s << endl;
}
for (auto s : sol.generatePalindromes("aab")) {
cout << s << endl;
}
for (auto s : sol.generatePalindromes("caracar")) {
cout << s << endl;
}
return 0;
}