LeetCode 2697: Lexicographically Smallest Palindrome
Problem Description
Explanation
To solve this problem, we can iterate through the string from both ends and make the characters at the corresponding positions equal by choosing the lexicographically smallest character. If the characters are already equal, we move to the next pair. After making the string a palindrome, if there are still remaining operations left, we can use them to make the string lexicographically smallest.
- Initialize two pointers
left
andright
at the beginning and end of the string, respectively. - While
left
is less than or equal toright
, compare characters at positionsleft
andright
. - If the characters are not equal, replace the character at position
left
with the lexicographically smaller character between the characters at positionsleft
andright
. - Decrement
right
after each comparison and incrementleft
only when necessary. - After making the string a palindrome, if there are remaining operations, update the string to make it lexicographically smallest.
Time complexity: O(n), where n is the length of the input string s
.
Space complexity: O(n) for storing the modified string.
Solutions
class Solution {
public String makePalindrome(String s) {
char[] chars = s.toCharArray();
int left = 0, right = s.length() - 1;
int ops = 0;
while (left <= right) {
if (chars[left] != chars[right]) {
chars[left] = chars[right] < chars[left] ? chars[right] : chars[left];
ops++;
}
left++;
right--;
}
if (ops > 0) {
left = 0;
right = s.length() - 1;
while (left <= right && ops > 0) {
if (chars[left] != 'a') {
chars[left] = 'a';
ops--;
}
if (chars[right] != 'a') {
chars[right] = 'a';
ops--;
}
left++;
right--;
}
}
return new String(chars);
}
}
Loading editor...