python3最优解法

查找两个字符串a,b中的最长公共子串

http://www.nowcoder.com/questionTerminal/181a1a71c7574266ad07f9739f791506

while True:
    try:
        s1 = input()
        s2 = input()
        if len(s1) > len(s2):    
            s2,s1 = s1,s2
        max = [0,'']    #存放找到的最大子串
        lenth = 1    #为截取字符串的长度
        for x in range(len(s1)):    #lenth最多自增到s1的长度,每次循环lenth自增1
            for i in range(len(s1)-lenth):    #循环截取s1,在s2中寻找是否有匹配
                if s1[i:i+lenth+1] in s2:    #如若在s2中找到
                    max = [lenth,s1[i:i+lenth+1]]    #存入max中
                    break
            if max[0] != lenth:    #如果lenth长度的子串不存在,必定lenth+1的子串也不存在
                break    #直接停止找寻子串
            lenth += 1
        print(max[1])
    except:
        break
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务