[LeetCode] Lexicographically Smallest Palindrome

2697. Lexicographically Smallest Palindrome

You are given a string s consisting of lowercase English letters, and you are allowed to perform operations on it. In one operation, you can replace a character in s with another lowercase English letter.

Your task is to make s a palindrome with the minimum number of operations possible. If there are multiple palindromes that can be made using the minimum number of operations, make the lexicographically smallest one.

A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.

Return the resulting palindrome string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
string makeSmallestPalindrome(string s) {
int l = 0, r = s.size() - 1;
while(l < r) {
if(s[l] != s[r]) {
s[l] = s[r] = min(s[l], s[r]);
}
l += 1, r -= 1;
}
return s;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/21/PS/LeetCode/lexicographically-smallest-palindrome/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.