zoukankan      html  css  js  c++  java
  • 【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'
  • 相关阅读:
    xml ui
    xml ui
    xml ui
    debug
    centOS7 mini配置linux服务器(一)安装centOs7
    数据结构之__链表
    数据结构之__队列
    数据结构之__栈
    在树莓派上使用 SSD1306 OLED 屏幕
    git官方手册
  • 原文地址:https://www.cnblogs.com/seyjs/p/12236372.html
Copyright © 2011-2022 走看看