45 lines
881 B
C++
45 lines
881 B
C++
|
|
#include <algorithm>
|
||
|
|
#include <limits>
|
||
|
|
#include <set>
|
||
|
|
#include <stdexcept>
|
||
|
|
#include <string>
|
||
|
|
|
||
|
|
using std::set;
|
||
|
|
using std::string;
|
||
|
|
using std::ranges::next_permutation;
|
||
|
|
using std::ranges::reverse;
|
||
|
|
using std::ranges::sort;
|
||
|
|
|
||
|
|
class Solution {
|
||
|
|
public:
|
||
|
|
string smallestPalindrome(string s, int k) {
|
||
|
|
|
||
|
|
string half = s.substr(0, s.size() / 2);
|
||
|
|
|
||
|
|
sort(half);
|
||
|
|
|
||
|
|
set<string> permutations;
|
||
|
|
|
||
|
|
do {
|
||
|
|
permutations.insert(half);
|
||
|
|
} while (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 string();
|
||
|
|
}
|
||
|
|
|
||
|
|
auto it = permutations.begin();
|
||
|
|
advance(it, k);
|
||
|
|
|
||
|
|
string mirroredHalf = *it;
|
||
|
|
reverse(mirroredHalf);
|
||
|
|
|
||
|
|
return *it + mirroredHalf;
|
||
|
|
}
|
||
|
|
};
|