LeetCode 1328. Break a Palindrome
考点 | 难度 |
---|---|
Greedy | Easy |
题目
Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.
Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.
A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, “abcc” is lexicographically smaller than “abcd” because the first position they differ is at the fourth character, and ‘c’ is smaller than ‘d’.
思路
iterate到中间位置,把所有不是a的字母改成a,最后一个改成b
答案
class Solution(object):
def breakPalindrome(self, pal):
n = len(pal)
for i in range(n//2):
if pal[i] != "a": return pal[:i] + "a" + pal[i+1:]
return pal[:-1] + "b" if n > 1 else ""