模式匹配的KMP算法代码

 

代码
#include<stdio.h>
#include
<string.h>
#define N 1001
void get_next(char T[],int next[],int T_Length)//计算出next的值
{
int i=1,j=0;next[1]=0;//注意i从1开始而j从0开始j比i小1
for(;i<T_Length;){
if(j==0||T[i]==T[j]){
i
++;j++;
next[i]
=j;
}
else j=next[j];
}
return ;
}
int main()
{
int i,j,T_Length,S_Length;
int next[N];
char T[N],S[N];
while(scanf("%s%s",T+1,S+1)!=EOF){
T_Length
=strlen(T);
S_Length
=strlen(S);
i
=j=1;
get_next(T,next,T_Length);
while(j<T_Length&&i<S_Length){
if(j==0||T[j]==S[i]){
i
++;j++;
}
else j=next[j];
}
if(j==T_Length)
printf(
"YES\n%d\n",i);
else printf("NO\n");
}
return 0;
}

 

posted @ 2010-07-16 10:33  戮微扬  阅读(171)  评论(0编辑  收藏  举报