kmp算法next计算方法C语言,KMP(next)算法c语言实现
时间: 2023-08-22 20:31:35 浏览: 167
KMP算法中的next数组计算方法如下:
```c
void getNext(char *p, int *next) {
int pLen = strlen(p);
next[0] = -1;
int k = -1;
int j = 0;
while (j < pLen - 1) {
if (k == -1 || p[j] == p[k]) {
++j;
++k;
if (p[j] != p[k]) {
next[j] = k;
} else {
next[j] = next[k];
}
} else {
k = next[k];
}
}
}
```
KMP算法的C语言实现如下:
```c
#include <stdio.h>
#include <string.h>
void getNext(char *p, int *next);
int kmp(char *s, char *p);
int main() {
char s[100], p[100];
printf("请输入主串:");
scanf("%s", s);
printf("请输入模式串:");
scanf("%s", p);
int pos = kmp(s, p);
if (pos == -1) {
printf("未找到匹配的子串\n");
} else {
printf("匹配的子串起始位置为:%d\n", pos);
}
return 0;
}
void getNext(char *p, int *next) {
int pLen = strlen(p);
next[0] = -1;
int k = -1;
int j = 0;
while (j < pLen - 1) {
if (k == -1 || p[j] == p[k]) {
++j;
++k;
if (p[j] != p[k]) {
next[j] = k;
} else {
next[j] = next[k];
}
} else {
k = next[k];
}
}
}
int kmp(char *s, char *p) {
int sLen = strlen(s);
int pLen = strlen(p);
int next[pLen];
getNext(p, next);
int i = 0, j = 0;
while (i < sLen && j < pLen) {
if (j == -1 || s[i] == p[j]) {
++i;
++j;
} else {
j = next[j];
}
}
if (j == pLen) {
return i - j;
} else {
return -1;
}
}
```
阅读全文