#include <stdio.h>
#include <stdlib.h>
int nextval[1000];
typedef struct{
char *base;
int length;
}HString;
void InitString(HString &H){
int n;
printf("please input the n:");
scanf("%d",&n);
H.base = (char *) malloc ( sizeof (char) * (n + 2));
if(!H.base)
return ;
getchar();
printf("please input the Array of string:\n");
for(int i = 1; i <= n; i ++){
scanf("%c",&H.base[i]);
}
H.length = n;
}
void Get_nextval(HString S){
int i = 1, j = 0;
while(i < S.length){
if(j == 0 || S.base[i] == S.base[j]){
++ i; ++ j;
if(S.base[i] != S.base[j]){
nextval[i] = j;
}
else{
nextval[i] = nextval[j];
}
}
else{
j = nextval[j];
}
}
}
int Index_KMP(HString H, HString S){
int i = 1, j = 1;
Get_nextval(S);
while(i < H.length && j < S.length){
if(j == 0 || S.base[j] == H.base[i]){
++ i; ++ j;
}
else{
j = nextval[j];
}
}
if(j >= S.length)
return i - S.length;
return 0;
}
int main(){
HString H,S;
int ans;
InitString(H);
InitString(S);
ans = Index_KMP(H,S);
if(!ans)
printf("Not Search The Same String \n");
else
printf("The Same String is %dth and %dth\n",ans + 1,ans + S.length);
return 0;
}
模式匹配_KMP
最新推荐文章于 2025-03-06 14:59:28 发布