0
点赞
收藏
分享

微信扫一扫

Python求两个字符串的最长公共子串&最长回文子串

def getcommonsubstr(str1,str2):
    #dp[i][j]表示以str1的第i位和str2的第j位往前倒序开始匹配的公共子串长度
    l1,l2=len(str1),len(str2)
    dp=[[0]*(l2+1) for _ in range(l1+1)]
    maxlength=0 #最大匹配长度,maxlength=max(map(max,dp))
    p=0 #匹配成功的末尾位的后一位
    for i in range(l1):
        for j in range(l2):
            if str1[i]==str2[j]:
                dp[i+1][j+1]=dp[i][j]+1
                if maxlength<dp[i+1][j+1]:
                	maxlength=dp[i+1][j+1]
                 	p=i+1                                                                                                                             
    return str1[p-maxlength:p]
def longest_palindrome_substr(str):
    return getcommomsubstr(str,str[::-1])      
举报

相关推荐

0 条评论