面试题:查找两个字符串的连续子串

 

 

 

def GetChild(data1,data2):
    maxLength=end=tempLength=0
    tempData={}

    # 选择出比较长字符串
    largest=data1
    other=data2
    if len(data2)>len(data1):
        largest=data2
        other=data1
        
    # 将比较长的字符串每个字符及位置存在字典中,便于查找
    for i in range(len(largest)):
        if largest[i] not in tempData :tempData[largest[i]]=[]
        tempData[largest[i]].append(i)

    # 遍历较短字符串准备找相同字符串
    for i in range(len(other)):
        # 如果较长字符串中没有就丢弃
        if other[i] not in  tempData:continue
        # 字符重复出现,其下标存在字典中List中
        indexList=tempData[other[i]]
        # 对重复字符遍历比较,查找字串
        for index in indexList:
            firsti=i+1
            tempLength=1
            j=index+1
            # 字串查找
            while firsti<len(other) and j<len(largest) and other[firsti]==largest[j]:
                tempLength+=1
                firsti+=1
                j+=1
            # 如果本次子串最长纪录下来
            if tempLength>maxLength:
                maxLength=tempLength
                end=j
    return largest[end-maxLength:end]

print(GetChild('likeyooooooooooou','loooookyou'))
print(GetChild('likeyou','lookyou'))


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值