0
点赞
收藏
分享

微信扫一扫

leecode 题目5 最长回文子串(python)

Soy丶sauce 2022-02-25 阅读 53

给你一个字符串 s,找到 s 中最长的回文子串。

示例 1:

示例 2:

  • 代码是根据B站上的一位up主写的
  • 使用动态规划算法
  • 从小字符串衍生相关字符串的状态
class Solution:
    def longestPalindrome(self, s: str) -> str:
        if not s:
            return s
        l = len(s)
        state = [[False for _ in range(l)] for _ in range(l)]

        max_length,index = 1,0
        for i in range(l):
            state[i][i] = True
        for j in range(1,l):
            for i in range(j):
                if s[i] == s[j]:
                    if j - i < 3:
                        state[i][j] = True
                    else:
                        state[i][j] = state[i+1][j-1]
                    temp_length = j - i + 1
                    if state[i][j]:
                        if temp_length > max_length:
                            max_length,index = temp_length,i
                    
        return s[index:index+max_length]
        


举报

相关推荐

0 条评论