[LeetCode] Smallest Palindromic Rearrangement I

3517. Smallest Palindromic Rearrangement I

You are given a palindromic string s.

Return the lexicographically smallest palindromic permutation of s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string smallestPalindrome(string s) {
vector<int> cnt(26);
for(auto& ch : s) cnt[ch-'a']++;
for(int i = 0, l = 0, r = s.length() - 1; i < 26; i++) {
while(cnt[i] >= 2) {
cnt[i] -= 2;
s[l++] = s[r--] = i + 'a';
}
if(cnt[i]) s[s.length()/2] = i + 'a';
}
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/04/14/PS/LeetCode/smallest-palindromic-rearrangement-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.