KMP

gebeng發表於2024-03-30

PMT:部分匹配表(Partial Match Table)
表示含義:t[0,i] 的前字尾最大匹配長度
image

s = input()
t = input()
n,m = len(s),len(t)
pmt = [0] * m
c = 0
for i in range(1,m):
    x = t[i]
    while c and t[c] != x:
        c = pmt[c - 1]
    if t[c] == x:
        c += 1
    pmt[i] = c

c = 0
for i in range(n):
    x = s[i]
    while c and t[c] != x:
        c = pmt[c - 1]
    if t[c] == x:
        c += 1
    if c == m:
        print(i - c + 1)
        c = pmt[c - 1]

"""
input:
12341234
1234
output:
0
4
"""

相關文章