longest-palindromic-substring

来源:互联网 发布:真空料理机 鱼汤 知乎 编辑:程序博客网 时间:2024/05/17 01:54

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

def longestPalindrome(S):   if len(S) == 0 or len(S) < 2:      return S   dp = [[False for _ in range(len(S))] for _ in range(len(S))]   res = ''   maxlen = 0   dp[0][0] = True   j = 0   while j < len(S):      dp[j][j] = True      i = 0      while i < j:         dp[i][j] = (j - i < 2 or dp[i + 1][j - 1]) and S[i] == S[j]         if dp[i][j] and j-i+1 > maxlen:            res = S[i:j+1]            maxlen = j-i+1         i += 1      j += 1   return resprint longestPalindrome("etretretdaadaad")


原创粉丝点击