KMP算法,结果得不出来
#include "stdio.h"#include "string.h"
void GetPreNext(char *s,int *next)
{
int i,j,length;
length=strlen(s);
j=0;
i=1;
next[1]=0;
while(i<=length)
{
if(j==0||s[i]==s[j])
{
i++;
j++;
if(s[i]!=s[j])
{
next[i]=j;
}
else
{
next[i]=next[j];
}
}
else
{
j=next[j];
}
}
}
int math(char *s,char *t,int *next)
{
int length_s,length_t;
int i,j;
i = 1;
j = 1;
length_s = strlen(s);
length_t = strlen(t);
if(length_s < length_t)
{
return -1;
}
else
{
while(i <= length_s && j <= length_t)
{
if(j==0||s[i]==t[j])
{
i++;
j++;
}
else
{
j=next[j];
}
}
if(j>length_t)
{
return i-j+1;
}
else
{
return -1;
}
}
}
void main()
{
char s[100]="zhonghuarenminggongheguo";
char t[100]="ing";
int next[100]={0},n;
GetPreNext(t,next);
n=math(s,t,next);
if(n==-1)
{
printf("Cannot find the string!\n");
}
else
{
printf("The position is %d\n",n);
}
}
当字符串比较短的时候能查的出来,当字符串比较长的时候查不出来。请高手帮忙改下!
[ 本帖最后由 小J 于 2010-3-24 17:43 编辑 ]