KMP匹配Python实现

def count_next(l):
    if len(l) == 1:
        return 1    
    for i in range(len(l)-1,0,-1):
        if l[:i] == l[-i:]:
            return i
    return 0
def get_next(l):
    o = [0]
    for i in range(len(l)):
        l1 = l[:i+1]
        o.append(count_next(l1))        
    return o
def KMP_lookup(s1,s2):
    c1,c2 = len(s1),len(s2)
    index = 0
    l = get_next(s2)
    o = []
    while index <= (c1-c2):
        c = 0
        for i in range(c2):
            if s1[index+i]!=s2[i]: 
                index += ((i+1)-l[i])
                break
            else:
                c += 1
        if c==c2:
            o.append(index)
            index += ((c2+1)-l[-1])
    if len(o)==0:
        return False,o
    else:
        return True,o
s1 = 'bacbababadababacambabacaddababacasdsd'
s2 = 'ababaca'
l1 = get_next(s2)
a,b = KMP_lookup(s1,s2)
if a:
    print(a)
    print(b)
else:
    print(a)

如果能匹配到则输出True,并输出匹配到的index

如果匹配不到则输出False

你可能感兴趣的:(KMP匹配Python实现)