【leetcode】1328. Break a Palindrome
题目如下:
Given a palindromic string
palindrome
, replace exactly one character by any lowercase English letter so that the string becomes the lexicographically smallest possible string that isn't a palindrome.After doing so, return the final string. If there is no way to do so, return the empty string.
Example 1:
Input: palindrome = "abccba" Output: "aaccba"Example 2:
Input: palindrome = "a" Output: ""Constraints:
1 <= palindrome.length <= 1000
palindrome
consists of only lowercase English letters.
解题思路:从左向右遍历palindrome,把第一个不是a的字符转换成a即可,并且要满足转换后的字符串不是回文字符串。
代码如下:
class Solution(object): def breakPalindrome(self, palindrome): """ :type palindrome: str :rtype: str """ for i in range(len(palindrome)): if palindrome[i] == 'a': continue v = palindrome[:i] + 'a' + palindrome[i+1:] if v == v[::-1]:continue return palindrome[:i] + 'a' + palindrome[i+1:] if len(palindrome) == 1: return '' elif palindrome[-1] == 'a': return palindrome[:-1] + 'b' return palindrome[:-1] + 'a'