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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM