首页 > 其他 > 详细

【leetcode】1328. Break a Palindrome

时间:2020-01-27 17:50:07      阅读:80      评论:0      收藏:0      [点我收藏+]

题目如下:

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

 

【leetcode】1328. Break a Palindrome

原文:https://www.cnblogs.com/seyjs/p/12236372.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!