zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):字符串类:第5题:最长回文子串:给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

    题目:
    最长回文子串:给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
    思路:
    思路较简单,需要考虑回文是奇数还是偶数的情况,但是小坑多,得一一调。
    程序:
    class Solution:
        def longestPalindrome(self, s: str) -> str:
            if not s:
                return s
            length = len(s) 
            if length == 1:
                return s
            if length > 1000:
                return null
            result = ''
            auxiliary = 0
            for index in range(1, length):
                index1 = index - 1
                index2 = index
                while index1 >= 0 and index2 < length and s[index1] == s[index2]:
                    index1 -= 1
                    index2 += 1
                if index2 - index1 + 1 > auxiliary:
                    auxiliary = index2 - index1 + 1
                    result = s[index1 + 1: index2]
                index3 = index - 1
                index4 = index + 1
                while index3 >= 0 and index4 < length and s[index3] == s[index4]:
                    index3 -= 1
                    index4 += 1
                if index4 - index3 + 1 > auxiliary:
                    auxiliary = index4 - index3 + 1
                    result = s[index3 + 1: index4]
            return result
  • 相关阅读:
    Kubernetes基础:Pod的详细介绍
    十分钟带你理解Kubernetes核心概念
    kubectl命令行工具用法详解
    GDPR给安全的影响
    开源软件会被云杀死吗 ?
    VMware前路难测,多个厂家群雄逐鹿
    如何实现linux+windows双系统启动
    IT行业——Linux
    i3 窗口管理器使 Linux 更美好
    在 Linux 中使用超级用户权限
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12842504.html
Copyright © 2011-2022 走看看