-
Notifications
You must be signed in to change notification settings - Fork 0
/
palindrome-reorder.cpp
65 lines (64 loc) · 1.32 KB
/
palindrome-reorder.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
65
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
map<char, int> memo;
for (auto c: s) {
memo[c]++;
}
if (s.size() % 2 == 0) {
// all letter counts must be even
bool ok = true;
for (auto [c, cnt]: memo) {
if (cnt % 2 == 1) {
ok = false;
break;
}
}
if (ok) {
string s1, s2;
for (auto [c, cnt]: memo) {
for (int i = 0; i < cnt / 2; i++) {
s1.push_back(c);
s2.push_back(c);
}
}
// s1 + reverse(s2) = palindrome
reverse(s2.begin(), s2.end());
cout << s1 + s2 << "\n";
} else {
cout << "NO SOLUTION" << "\n";
}
} else {
// all letter counts except one must be even
bool ok = false;
char mid;
for (auto [c, cnt]: memo) {
if (cnt % 2 == 1) {
if (!ok) {
ok = true;
mid = c;
} else {
ok = false;
break;
}
}
}
if (ok) {
string s1, s2;
for (auto [c, cnt]: memo) {
for (int i = 0; i < cnt / 2; i++) {
s1.push_back(c);
s2.push_back(c);
}
}
// s1 + mid + reverse(s2) = palindrome
reverse(s2.begin(), s2.end());
cout << s1 + mid + s2 << "\n";
} else {
cout << "NO SOLUTION" << "\n";
}
}
return 0;
}