leetcode1328. Break a Palindrome

Posted seyjs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1328. 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

 

以上是关于leetcode1328. Break a Palindrome的主要内容,如果未能解决你的问题,请参考以下文章

1328. Break a Palindrome

leetcode1328

[LeetCode] Integer Break

LeetCode 343. Integer Break

leetcode168

Word Break