70090a66e7
Replace global using declarations with explicit std:: qualifications. Update ranges algorithms usage to std::ranges and fix permutation iterator offset to correctly handle 1-based k indexing.
39 lines
833 B
C++
39 lines
833 B
C++
#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);
|
|
|
|
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();
|
|
advance(it, k - 1);
|
|
|
|
std::string mirroredHalf = *it;
|
|
std::ranges::reverse(mirroredHalf);
|
|
|
|
return *it + mirroredHalf;
|
|
}
|
|
};
|