feat: add solution for smallest palindromic rearrangement ii
- add problem 3518 implementation - add build configuration with debug and release modes - add test cases and examples - add makefile for problem-specific build workflow
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
#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;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user