KMP 算法

KMP 算法

简介

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution:
def resolve(self, haystack: str, needle: str) -> int:
a = len(needle)
b = len(haystack)
if a == 0:
return 0
next_array = self.get_next(a, needle)
p = -1
for j in range(b):
while p >= 0 and needle[p + 1] != haystack[j]:
p = next_array[p]
if needle[p + 1] == haystack[j]:
p += 1
if p == a - 1:
return j - a + 1
return -1

@staticmethod
def get_next(a, needle):
next_array = ['' for i in range(a)]
k = -1
next_array[0] = k
for i in range(1, len(needle)):
while k > -1 and needle[k + 1] != needle[i]:
k = next_array[k]
if needle[k + 1] == needle[i]:
k += 1
next_array[i] = k
return next_array


txt = "ABABDABACDABABCABAB"
pat = "ABABCABAB"
s = Solution()
print(s.resolve(txt,pat))

参考资料

视频图解

源码


KMP 算法
https://wangqian0306.github.io/2022/kmp/
作者
WangQian
发布于
2022年9月13日
许可协议