首页 > 其他 > 详细

查找最长公共子串

时间:2019-08-06 11:32:52      阅读:76      评论:0      收藏:0      [点我收藏+]

大疆测试08/02编程题

 

 技术分享图片

 

 

def getNumofCommonSubstr(str1, str2):
    # 先确保str1是较短的字符串
    if len(str2)<len(str1):
        str1,str2 = str2,str1
    lstr1 = len(str1)
    lstr2 = len(str2)
    record = [[0 for i in range(lstr2)] for j in range(lstr1)] 
    maxNum = 0   # 最长匹配长度
    p = 0    # 匹配的起始位

    for i in range(lstr1):
        for j in range(lstr2):
            if str1[i] == str2[j]:
                if i>0 and j>0:
                    # 相同则累加
                    record[i][j] = record[i-1][j-1] + 1
                else:
                    record[i][j] = 1
                    
                if record[i][j] > maxNum:
                    # 获取最大匹配长度
                    maxNum = record[i][j]
                    # 记录最大匹配长度的终止位置
                    p = i + 1
    return str1[p-maxNum:p]

  

if __name__ == ‘__main__‘:
    str1 = input()
    str2 = input()
    res = getNumofCommonSubstr(str1, str2)
    print(res) 

  

查找最长公共子串

原文:https://www.cnblogs.com/ivyharding/p/11307876.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!