python kmp算法简单实现

def getnext(a,next):
    al = len(a)
    next[0] = -1
    k = -1
    j = 0
    while j < al-1:
        if k == -1 or a[j] == a[k]:
            j += 1
            k += 1
            next[j] = k
        else:
            k = next[k]

def KmpSearch(a,b):
    i = j = 0
    al = len(a)
    bl = len(b)
    while i < al and j < bl:
        if j == -1 or a[i] == b[j]:
            i += 1
            j += 1
        else:
            j = next[j]
    if j == bl:
        return i-j
    else:
        return -1

a = 'ABABCABDABBGAFDSBVSABDABB'
b = 'ABDABB'
next = [0]*len(b)
getnext(b,next)
t = KmpSearch(a,b)
print(next)
print(t)

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/u010041824/article/details/70786733
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞