求最长回文串

来源:互联网 发布:c语言异步调用 编辑:程序博客网 时间:2024/05/16 10:15

之前写的很复杂,以后从简从精

import numpy as npclass Solution(object):    def longestPalindrome(self, s):        maxlen, start, stop = 0, 0, 0        n = len(s)        dp = np.eye(n)        for j in range(n):            i = j            while i >= 0:                if s[i] == s[j] and (j - i <= 2 or dp[i + 1][j - 1]):                    dp[i][j] = 1                    if j - i + 1 > maxlen:                        maxlen = j - i + 1                        start = i                        stop = j                i = i - 1        return s[start:stop+1]

原文链接,引用学习,如有侵权,联系必删
方法,动态规划,if s[i] == s[j] and (j - i <= 2 or dp[i + 1][j - 1]):,这行代码是关键,如果第i个字符和第j个字符相等,那么dp[i][j]=1前提是j-i<=2和dp[i+1][j-1]。
循环的边界,以j为终点,i从终点依次减小。

原创粉丝点击