直接上模板:
#include<stdio.h>
#include<string.h>
void getNext(int next[], char str[]){
int i, j = -1, len = strlen(str);
next[0] = -1;
for(i = 1; i<len; i++){
while(j != -1 && str[i] != str[j+1])
j = next[j];
if(str[i] == str[j+1])
j++;
next[i] = j;
}
}
void kmp(char text[], char pattern[]){
//pattern为要匹配的子串
int next[1000];
getNext(next, pattern);
int i, j = -1, ans = 0, m = strlen(text), n = strlen(pattern);
for(i = 0; i<m; i++){
while(j != -1 && text[i] != pattern[j+1])
j = next[j];
if(text[i] == pattern[j+1])
j++;
if(j == n-1){
ans++;
j = next[j];
}
}
printf("Matched substring is %d\n", ans);
}
int main(){
char text[1000], pattern[1000];
printf("text:");
gets(text);
printf("pattern:");
gets(pattern);
kmp(text, pattern);
return 0;
}