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

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

https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506


a = raw_input()
b = raw_input()
这个是我参考别人的,在他的基础上修复了字符串为1的情况不打印结果的bug,增加了两个字符串长度相同时,输出两个字符串里面更靠前的公共子串。
def f(a,b):    
    if len(a)>len(b):
        a,b=b,a
    res = ''
    for i in range(0,len(a)+1):
        for j in range(i,len(a)):
            if a[i:j+1] in b and j+1-i>len(res):
                res = a[i:j+1]
    ml = len(res)
    ls = {}
    if len(a) == len(b):
        #下来利用公共子串在字符串出现的位置作为字典的key,公共子串作为value来实现
        for i in range(len(a)):
            if a[i:i+ml] in b and i+ml <len(a)+1:
                ls[i] = a[i:i+ml]
        for j in range(len(b)):
            if b[j:j+ml] in a and j+ml <len(b)+1:
                ls[j] = b[j:j+ml]
        ls2 = sorted(ls.keys())
        print ls[0]
    else:
        print res 
f(a, b)

全部评论

相关推荐

牛客ID:561366855:期望薪资多少?难以相信这简历找不到工作。说明二本电子信息专业想对口就业非常难。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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