KMP算法C语言实现
时间: 2024-03-21 09:36:10 浏览: 28
KMP算法是一种字符串匹配算法,用于在一个主串中查找一个模式串的出现位置。下面是KMP算法的C语言实现:
```c
#include <stdio.h>
#include <string.h>
void getNext(char* pattern, int* next) {
int len = strlen(pattern);
next[0] = -1;
int i = 0, j = -1;
while (i < len - 1) {
if (j == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
int kmp(char* text, char* pattern) {
int len1 = strlen(text);
int len2 = strlen(pattern);
int* next = (int*)malloc(sizeof(int) * len2);
getNext(pattern, next);
int i = 0, j = 0;
while (i < len1 && j < len2) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
} else {
j = next[j];
}
}
free(next);
if (j == len2) {
return i - j;
} else {
return -1;
}
}
int main() {
char text[] = "ABABABABCABABABAABABABABD";
char pattern[] = "ABABABA";
int pos = kmp(text, pattern);
if (pos != -1) {
printf("Pattern found at position: %d\n", pos);
} else {
printf("Pattern not found.\n");
}
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)