#include <stdio.h>
#include <string.h>
#include <iostream>
void getnext(int next[], char s[], int l) {
int i = 1, j = 0;
next[1] = 0;
while (i < l) {
if (j == 0 || s[i] == s[j]) {
i++;
j++;
next[i] = j;
} else
j = next[j];
}
}
int KMP(char s1[], char s2[], int l1, int l2, int next[]) {
int i, j;
i = j = 1;
while (i <= l1 && j <= l2) {
if (j == 0 || s1[i] == s2[j]) {
i++;
j++;
} else
j = next[j];
}
if (j > l2) return (i - l2);
return 0;
}
int main() {
int next[10001], ans;
char s1[10001], s2[10001], l1, l2;
scanf("%s", s1 + 1);
scanf("%s", s2 + 1);
l1 = strlen(s1 + 1);
l2 = strlen(s2 + 1);
getnext(next, s2, l2);
ans = KMP(s1, s2, l1, l2, next);
if (ans != 0)
printf("%d/n", ans);
else
printf("No!/n");
system("pause");
return 0;
}
KMP算法(附C语言实现)
最新推荐文章于 2025-11-25 16:42:54 发布
本文介绍了一个使用KMP算法进行字符串匹配的C/C++程序实例。该程序定义了两个函数:getnext()用于预处理模式串生成next数组;KMP()则实现核心的KMP搜索算法。通过输入两个字符串,程序能够找出模式串在主串中的位置。
&spm=1001.2101.3001.5002&articleId=4808772&d=1&t=3&u=47d8ce999bc3475b8d3babedeed8a821)
6844

被折叠的 条评论
为什么被折叠?



