用C语言写出KMP算法
时间: 2023-05-24 07:05:17 浏览: 96
KMP算法实现的C语言代码如下:
#include <stdio.h>
#include <string.h>
void getNext(char* p,int* next)
{
int j = 0, k = -1;
next[0] = -1;
while (p[j] != '\0') {
if (k == -1 || p[j] == p[k]) {
++j;
++k;
next[j] = k;
}
else {
k = next[k];
}
}
}
int KMP(char* s, char* p)
{
int i = 0, j = 0;
int sLen = strlen(s);
int pLen = strlen(p);
int next[pLen];
getNext(p, next);
while (i < sLen && j < pLen) {
if (j == -1 || s[i] == p[j]) {
++i;
++j;
}
else {
j = next[j];
}
}
if (j == pLen) {
return i - j;
}
return -1;
}
int main()
{
char s[] = "ABABDABACDABABCABAB";
char p[] = "ABABCABAB";
int index = KMP(s, p);
printf("模式串在主串中的位置是: %d\n", index);
return 0;
}
阅读全文