Files

44 lines
993 B
C++
Raw Permalink Normal View History

#include <algorithm>
#include <limits>
#include <set>
#include <stdexcept>
#include <string>
class Solution {
public:
std::string smallestPalindrome(std::string s, int k) {
std::string half = s.substr(0, s.size() / 2);
char middle = (s.size() % 2 == 1) ? s[s.size() / 2] : '\0';
std::ranges::sort(half);
std::set<std::string> permutations;
do {
permutations.insert(half);
} while (std::ranges::next_permutation(half).found);
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) {
return std::string();
}
auto it = permutations.begin();
std::advance(it, k - 1);
std::string mirroredHalf = *it;
std::ranges::reverse(mirroredHalf);
if (middle != '\0') {
return *it + std::string(1, middle) + mirroredHalf;
}
return *it + mirroredHalf;
}
};