KMP模式匹配算法c语言代码
时间: 2024-04-02 07:29:35 浏览: 93
kmp模式匹配算法c语言源代码
4星 · 用户满意度95%
KMP模式匹配算法是一种高效的字符串匹配算法,它通过预处理模式串,构建一个部分匹配表(Next数组),来避免不必要的回溯操作。下面是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[0] = -1;
while (i < len) {
if (j == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
int kmpSearch(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 index = kmpSearch(text, pattern);
if (index != -1) {
printf("Pattern found at index %d\n", index);
} else {
printf("Pattern not found\n");
}
return 0;
}
```
阅读全文