From 8d60ff900afe2962a7708ebb422005e2012f7132 Mon Sep 17 00:00:00 2001 From: Ariel Date: Sun, 14 Jan 2024 11:30:29 +0800 Subject: [PATCH] Create kmp.py --- string/kmp.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 string/kmp.py diff --git a/string/kmp.py b/string/kmp.py new file mode 100644 index 0000000..3f1c397 --- /dev/null +++ b/string/kmp.py @@ -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