[LeetCode] 2697. Lexicographically Smallest Palindrome

发布时间 2023-12-14 05:16:38作者: CNoodle

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.

Example 1:
Input: s = "egcfe"
Output: "efcfe"
Explanation: The minimum number of operations to make "egcfe" a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is "efcfe", by changing 'g'.

Example 2:
Input: s = "abcd"
Output: "abba"
Explanation: The minimum number of operations to make "abcd" a palindrome is 2, and the lexicographically smallest palindrome string we can get by modifying two characters is "abba".

Example 3:
Input: s = "seven"
Output: "neven"
Explanation: The minimum number of operations to make "seven" a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is "neven".

Constraints:
1 <= s.length <= 1000
s consists of only lowercase English letters.

字典序最小回文串。

给你一个由 小写英文字母 组成的字符串 s ,你可以对其执行一些操作。在一步操作中,你可以用其他小写英文字母 替换 s 中的一个字符。
请你执行 尽可能少的操作 ,使 s 变成一个 回文串 。如果执行 最少 操作次数的方案不止一种,则只需选取 字典序最小 的方案。
对于两个长度相同的字符串 a 和 b ,在 a 和 b 出现不同的第一个位置,如果该位置上 a 中对应字母比 b 中对应字母在字母表中出现顺序更早,则认为 a 的字典序比 b 的字典序要小。
返回最终的回文字符串。

思路

这道题就是处理回文串那一类的题,唯一需要留意的是当左右指针指向的元素不一样的时候,把字典序较大的那一个字母替换成字典序较小的那一个。

复杂度

时间O(n)
空间O(n)

代码

Java实现

class Solution {
    public String makeSmallestPalindrome(String s) {
        char[] letters = s.toCharArray();
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            char l = letters[left];
            char r = letters[right];
            if (l > r) {
                letters[left] = r;
            } else {
                letters[right] = l;
            }
            left++;
            right--;
        }
        return new String(letters);
    }
}