请教关于kmp算法,解决立即给分!
redez 2004-11-21 11:06:48 要求:
1)文章存于一个文本文件中。待统计的词汇集合要一次输入完毕,即统计工作必须在程序的一次运行之后就全部完成。程序的输出结果是每个词的出现次数和出现位置所在的行号,格式自行设计。
2)要求采用基于KMP的算法实现。
3)整个统计过程只对文章文字扫描一遍以提高效率。
我编的程序为
#include<stdio.h>
#include<string.h>
void get_next(char *ch,int *next)
{
int i=1,j=0;
while(i<strlen(ch))
{
if(j==0||ch[i]==ch[j]) { i++; j++; next[i]=j; }
else j=next[j];
}
}
int Index_kmp(char *str,char *ch,int *next)
{
int i=0,j=0;
while(j<strlen(ch)&&i<strlen(str))
{
if(str[i]==ch[j]) { j++; i++; }
else
{
if(j==0) i++;
else j=next[j];
}
}
if(j>=strlen(ch)) return (i-j+1);
else return 0;
}
void main()
{
FILE *fp;
char str[100],ch[100],stren[100];
int i=0,m=0,j=0,k=0,next[100];
next[0]=100; next[1]=0;
if((fp=fopen("A.txt","r"))==NULL)
{
printf("File cann't be openen!");
}
while(!feof(fp))
str[i++]=fgetc(fp);
fclose(fp);
printf("\n File A contents are :\n");
printf("%s",str);
printf("\nPlease input the string:\n");
gets(ch);
m=strlen(ch);
get_next(ch,next);
if((i=Index_kmp(str,ch,next))==0)
printf("Nothing about the text's matching\n");
else
{
printf("\nThe position of the matching word is the");
printf(" %dth\n",i);
printf(" %s",&str[i+m-1]);
getchar();
}
}
现在只能查找第一次匹配的位置不能找到所有的匹配的词的次数和出现位置,请问怎么改才能实现
上面的功能?