串的kmp算法c完整代码
时间: 2024-04-17 16:21:51 浏览: 159
KMP算法代码
5星 · 资源好评率100%
KMP算法是一种字符串匹配算法,用于在一个主串中查找一个模式串的出现位置。下面是KMP算法的C语言完整代码:
```c
#include <stdio.h>
#include <string.h>
void getNext(char* pattern, int* next) {
int len = strlen(pattern);
int i = 0, j = -1;
next = -1;
while (i < len) {
if (j == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
int kmp(char* text, char* pattern) {
int textLen = strlen(text);
int patternLen = strlen(pattern);
int i = 0, j = 0;
int* next = (int*)malloc(sizeof(int) * patternLen);
getNext(pattern, next);
while (i < textLen && j < patternLen) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
} else {
j = next[j];
}
}
free(next);
if (j == patternLen) {
return i - j;
} else {
return -1;
}
}
int main() {
char text[] = "ABABABABCABABABA";
char pattern[] = "ABABCABAB";
int result = kmp(text, pattern);
if (result != -1) {
printf("Pattern found at index %d\n", result);
} else {
printf("Pattern not found\n");
}
return 0;
}
```
阅读全文