2026-07-29 19:35:44 +04:00
|
|
|
#include <algorithm>
|
|
|
|
|
#include <limits>
|
|
|
|
|
#include <set>
|
|
|
|
|
#include <stdexcept>
|
|
|
|
|
#include <string>
|
|
|
|
|
|
|
|
|
|
class Solution {
|
|
|
|
|
public:
|
2026-07-29 20:15:10 +04:00
|
|
|
std::string smallestPalindrome(std::string s, int k) {
|
2026-07-29 19:35:44 +04:00
|
|
|
|
2026-07-29 20:15:10 +04:00
|
|
|
std::string half = s.substr(0, s.size() / 2);
|
2026-07-29 21:12:36 +04:00
|
|
|
char middle = (s.size() % 2 == 1) ? s[s.size() / 2] : '\0';
|
2026-07-29 19:35:44 +04:00
|
|
|
|
2026-07-29 20:15:10 +04:00
|
|
|
std::ranges::sort(half);
|
2026-07-29 19:35:44 +04:00
|
|
|
|
2026-07-29 20:15:10 +04:00
|
|
|
std::set<std::string> permutations;
|
2026-07-29 19:35:44 +04:00
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
permutations.insert(half);
|
2026-07-29 20:15:10 +04:00
|
|
|
} while (std::ranges::next_permutation(half).found);
|
2026-07-29 19:35:44 +04:00
|
|
|
|
|
|
|
|
if (permutations.size() > std::numeric_limits<int>::max()) {
|
|
|
|
|
throw std::overflow_error("Number of permutations exceeds int limit");
|
|
|
|
|
}
|
|
|
|
|
int size = static_cast<int>(permutations.size());
|
|
|
|
|
|
|
|
|
|
if (k > size) {
|
2026-07-29 20:15:10 +04:00
|
|
|
return std::string();
|
2026-07-29 19:35:44 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
auto it = permutations.begin();
|
2026-07-29 21:12:36 +04:00
|
|
|
std::advance(it, k - 1);
|
2026-07-29 19:35:44 +04:00
|
|
|
|
2026-07-29 20:15:10 +04:00
|
|
|
std::string mirroredHalf = *it;
|
|
|
|
|
std::ranges::reverse(mirroredHalf);
|
2026-07-29 19:35:44 +04:00
|
|
|
|
2026-07-29 21:12:36 +04:00
|
|
|
if (middle != '\0') {
|
|
|
|
|
return *it + std::string(1, middle) + mirroredHalf;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-29 19:35:44 +04:00
|
|
|
return *it + mirroredHalf;
|
|
|
|
|
}
|
|
|
|
|
};
|