#include
#include
void Index(char S[],char T[],int pos,int next[])//利用模式串T的next函式求T在主串S中第pos個字符之后的位置的KMP演算法。
{ //其中,T非空,1<=pos<=S[0]
int i=pos,j=1;
while(i<=S[0]&&j<=T[0])
{ if(j==0||S[i]==T[j])
{ ++i;
++j;
}
else j=next[j];
}
if(j>=T[0]) printf("模式串在主串中的位置是: %3d",i-T[0]);
else printf("主串中不存在和模式串相等的字串");
}
void main()
{char S[]=" ababbaabaa";//0號單元存放字串中字符的個數
char T[]=" aab";//0號單元存放字串中字符的個數
int i,j,pos=0;
int next[100];//next[i]表示當模式中第i個字符和主串中相應的字符‘失配’時,
//在模式串中需重新和主串中該字符進行比較的字符的位置
S[0]=strlen(S)-1;
T[0]=strlen(T)-1;
printf("S[0]=%d",S[0]);
printf("T[0]=%d",T[0]);
i=1;
next[1]=0;
j=0;
while(i{ if(j==0||T[i]==T[j])
{ ++i;
++j;
next[i]=j;
}
else j=next[j];
}
for(i=1;i<=T[0];i++)
printf("%3d",next[i]);
printf("請輸入您要從主串中的哪個字符開始查找:");
scanf("%d",&pos);
Index(S,T,pos,next);
}
//可以運行,我剛做好的
uj5u.com熱心網友回復:
有什么問題嗎?問題描述!轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/27610.html
標籤:基礎類
上一篇:geany編輯器
