#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语言实现)
最新推荐文章于 2022-07-11 14:35:27 发布