python 实现 KMP算法

def kmp(s,t):
    lens = len(s)
    lent = len(t)
    if lens < lent:
        return -1
    i=0
    j=0
    newlist = [-1 for i in range(lent)]
    getNext(t,newlist)

    while i < lens:
        if j == -1 or s[i] == t[j]:
            i = i+1
            j = j+1

        else:
            j = newlist[j]

        if j==lent:
            return i-lent

    return -1
'''方法getNext获得待匹配字符串的数组''' 方法1
def getNext(s,newlist):
    j = 0
    k = -1
    newlist[0] = -1
    while j
def KMP(s,p):
    l = len(s)
    m = len(p)
    F = [-1 for i in range(m)]
    getNext(p,F)
    print(F)
    i=0
    j=0
    while i=0:
            j = F[j]


        if s[i] == s[j+1]:
            F[i] = j+1


        else:
            F[i] = -1


  

    

你可能感兴趣的:(python 实现 KMP算法)