KMP算法

def get_next(str):
    i,j,m,next=1,0,len(str),[0,]#i位置之前包括i位置的前后缀的最大公共子串
    while i<m:
        if str[i]==str[j]:
            next.append(j+1)
            i+=1
            j+=1
        elif j!=0:
            j=next[j-1]
        else:
            next.append(0)
            i+=1
    return next


def KMP_algorithm(string, substring):
    '''
    KMP字符串匹配的主函数
    若存在字串返回字串在字符串中开始的位置下标,或者返回-1
    '''
    pnext = get_next(substring)
    
    n = len(string)
    m = len(substring)
    i, j = 0, 0
    while (i<n) and (j<m):
        if (string[i]==substring[j]):
            i += 1
            j += 1
        elif (j!=0):
            j = pnext[j-1]
        else:
            i += 1
    if (j == m):
        return i-j
    else:
        return -1

if __name__ == "__main__":
    string = 'abcxabcdabcdabcy'
    substring = 'abcdabcy'
    out = KMP_algorithm(string, substring)
    print(out)

KMP链接:小白之KMP算法详解及python实现

posted on 2019-03-03 17:20  wzc521  阅读(100)  评论(0)    收藏  举报

导航