KMP算法:
next函数如图所示:
#include <iostream>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <cstring>
int next[100];
int getnext(char t[]){
int i = 0,j = -1;
next[0] = -1;
while(i < strlen(t)-1){
if(j == -1 || t[i] == t[j]){
i++;
j++;
next[i] = j;
}else
j = next[j];
}
for(int i = 0;i < strlen(t);i++){
printf("%d ",next[i]);
}
printf("\n");
}
int main(){
char s[100],t[100];
/* s是原始串,t是被匹配串 */
int i,j;
while(scanf("%s%s",s,t) != EOF){
memset(next,0,sizeof(next));
getnext(t);
i = 0,j = 0;
int lens = strlen(s),lent = strlen(t);
while(i < lens){
if((j == -1) || (s[i] == t[j])){
i++;
j++;
if(j == lent){
printf("%d ",i - lent);
j = 0;
}
}
else{
j = next[j];
}
}
printf("\n");
}
system("pause");
}