码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】1328. Break a Palindrome

时间:2020-01-27 19:23:10      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:sel   span   代码   sts   bre   The   HERE   string   lis   

题目如下:

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

标签:sel   span   代码   sts   bre   The   HERE   string   lis   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!