1
0
Fork 0

Create kmp.py

This commit is contained in:
Ariel 2024-01-14 11:30:29 +08:00 committed by GitHub
parent 8f0bea0162
commit 8d60ff900a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 29 additions and 0 deletions

29
string/kmp.py Normal file
View File

@ -0,0 +1,29 @@
def kmp(s, t): # find all occurrences of t in s
n = len(s)
m = len(t)
next = [-1]
j = -1
i = 0
while i < m:
if j == -1 or t[i] == t[j]:
i += 1
j += 1
if i != m and t[j] == t[i]:
next.append(next[j])
else:
next.append(j)
else:
j = next[j]
res = []
i = 0
j = 0
while i < n and j < m:
if j == -1 or s[i] == t[j]:
i += 1
j += 1
if j == m:
res.append(i - j)
j = next[j]
else:
j = next[j]
return res