面试题精选:KMP算法

0 阅读1分钟

字符串匹配中的经典KPM算法:

简单说:

  • src 的游标不变
  • dest 没匹配上就快速回退,匹配上就跟着 src 一起往前走

B8C3B3E1-E583-4994-A9B2-344178075326.png

def get_next(dest):
    N = len(dest)
    next = [-1] * N
    j = -1
    for i in range(1, N):
        while j!=-1 and dest[j+1]!=dest[i]:
            j = next[j]
        if dest[j+1]==dest[i]:
            j += 1
            next[i] = j
    return next



def strstr(src, dest):
    N, M = len(src), len(dest)
    next = get_next(dest)
    j = -1
    for i in range(N):
        while j!=-1 and dest[j+1]!=src[i]:
            j = next[j]
        if dest[j+1]==src[i]:
            j += 1
        if j+1==M:
            return i - M + 1
    return -1



print(strstr('abcdefghijk', 'def'))
print(strstr('abcdefghijk', 'abcdef'))
print(strstr('abcdefghijk', 'defk'))

# 3
# 0
# -1