kmp算法实现字符串匹配的完整代码
时间: 2024-04-25 19:18:39 浏览: 27
KMP算法是一种高效的字符串匹配算法,它通过预处理模式串,构建next数组,来实现在文本串中快速定位匹配的位置。下面是KMP算法的完整代码实现:
```python
def get_next(pattern):
next = [-1] * len(pattern)
i, j = 0, -1 or pattern[i] == pattern[j]:
i += 1
j += 1
next[i] = j
else:
j = next[j]
return next
def kmp_search(text, pattern):
next = get_next(pattern)
i, j = 0, 0
while i < len(text) and j < len(pattern):
if j == -1 or text[i] == pattern[j]:
i += 1
j += 1
else:
j = next[j]
if j == len(pattern):
return i - j
else:
return -1
# 测试代码
text = "ABABABABCABABABABABABD"
pattern = "ABABABA"
index = kmp_search(text, pattern)
print("匹配位置:", index)
```
以上是KMP算法的Python实现代码。其中,`get_next`函数用于构建模式串的next数组,`kmp_search`函数用于在文本串中进行匹配。测试代码中给出了一个示例,输出匹配位置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)