diff options
Diffstat (limited to '01_introductory_problems/string_reorder_1743.cpp')
| -rw-r--r-- | 01_introductory_problems/string_reorder_1743.cpp | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/01_introductory_problems/string_reorder_1743.cpp b/01_introductory_problems/string_reorder_1743.cpp new file mode 100644 index 0000000..d22041d --- /dev/null +++ b/01_introductory_problems/string_reorder_1743.cpp | |||
| @@ -0,0 +1,38 @@ | |||
| 1 | #include <algorithm> | ||
| 2 | #include <array> | ||
| 3 | #include <iostream> | ||
| 4 | #include <iterator> | ||
| 5 | #include <sstream> | ||
| 6 | #include <string> | ||
| 7 | |||
| 8 | int main() { | ||
| 9 | std::array<size_t, 26> a{}; | ||
| 10 | std::string s; | ||
| 11 | std::cin >> s; | ||
| 12 | for (auto c : s) a[c-'A']++; | ||
| 13 | |||
| 14 | size_t i{0}, j{1}, tot{s.size()}, c{99}; | ||
| 15 | std::stringstream ss{}; | ||
| 16 | while (*std::max_element(a.begin(), a.end()) <= tot / 2) { | ||
| 17 | while (a[i] == 0) i++; | ||
| 18 | while (a[j] == 0 || j <= i) j++; | ||
| 19 | c = i == c ? j : i; | ||
| 20 | ss << (char)('A' + c); | ||
| 21 | a[c]--; | ||
| 22 | tot--; | ||
| 23 | } | ||
| 24 | |||
| 25 | j = std::distance(a.begin(), std::max_element(a.begin(), a.end())); | ||
| 26 | while (a[j] > 1) { | ||
| 27 | if (tot == a[j]) { | ||
| 28 | std::cout << "-1\n"; | ||
| 29 | return 0; | ||
| 30 | } | ||
| 31 | while (a[i] == 0 || i == j) i++; | ||
| 32 | ss << (char)('A' + j) << (char)('A' + i); | ||
| 33 | a[i]--; | ||
| 34 | a[j]--; | ||
| 35 | tot -= 2; | ||
| 36 | } | ||
| 37 | std::cout << ss.str() << (char)('A' + j) << "\n"; | ||
| 38 | } | ||
