面試題:查找兩個字符串的連續子串

 

 

 

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'))


 

發佈了36 篇原創文章 · 獲贊 6 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章