leetcode 5. Longest Palindromic Substring

def longestPalindrome(s):

    # 建立DP array size is len(arr)*len(arr)
    dp = [[False]*len(s) for i in range(len(s))]
    # 初始化 start end 指针
    StartIndex = 0
    EndIndex = 0
    # dp算法填充表格,start 为行 end为列 要右上部分
    for i in range(len(s)):
        start = i
        end = i
        while start>=0:
            #对角线上的都是T
            if start==end:
                dp[start][end] = True
            #如果相邻,就不用了看中间的了
            elif start+1==end:
                dp[start][end] = s[start]==s[end]
            #不相邻,看看首先是不是相等,相等然后向中间看是否相等
            else:
                dp[start][end] = s[start]==s[end] and dp[start+1][end-1]
            if dp[start][end] and (end-start+1)>(EndIndex-StartIndex+1):
                StartIndex = start
                EndIndex = end
            start-=1

    return s[StartIndex:EndIndex+1]
a = 'akbka'
print(longestPalindrome(a))

 

你可能感兴趣的:(Leetcode刷题记录)