用python写个KMP算法
时间: 2023-04-01 18:01:55 浏览: 231
您好,我是C知道,可以回答您的问题。KMP算法是一种字符串匹配算法,可以在一个文本串S内查找一个模式串P的出现位置。以下是用Python实现KMP算法的代码:
```python
def kmp_search(text, pattern):
n = len(text)
m = len(pattern)
if m == :
return
next = get_next(pattern)
j =
for i in range(n):
while j > and text[i] != pattern[j]:
j = next[j - 1]
if text[i] == pattern[j]:
j += 1
if j == m:
return i - m + 1
return -1
def get_next(pattern):
m = len(pattern)
next = [] * m
j =
for i in range(1, m):
while j > and pattern[i] != pattern[j]:
j = next[j - 1]
if pattern[i] == pattern[j]:
j += 1
next[i] = j
return next
```
希望能帮到您。
阅读全文