算法是我自己想的,写出来之后也没有再优化,仅供您参考。
KMP算法链接
#include<stdio.h>
#define MAXSIZE 30
typedef struct {
char ch[MAXSIZE+1];
int length;
}sstring;
void setdata(sstring &w,char data){
w.ch[w.length]=data;
}
void appear(sstring S){
printf("\n串内元素为:");
for(int i=0;i<S.length;i++)
printf("%c",S.ch[i+1]);
printf("\n串内元素有%d个\n\n",S.length);
}
int bmw(sstring S,sstring L,int i,int j){
while(S.ch[i]==L.ch[j]){
if(i<=S.length && j==L.length)
return 1;
if(i==S.length && j<L.length)
return 0;
i++;
j++;
}
}
int bfsuan(sstring S,sstring L,int w){
int i=w,j=1;
while(i<=S.length && j<=L.length){
int ss=bmw(S,L,i,j);
if(ss==1)
return i;
i++;
}
return 0;
}
void main(){
char data;
int location;
printf("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n");
sstring S;
sstring L;
S.length=L.length=0;
printf("请输入主串内的元素(以#结束):\n");
scanf("%c",&data);
while(data!='#'){
S.length++;
setdata(S,data);
scanf("%c",&data);
}
appear(S);
printf("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n\n");
printf("请输入副串内的元素(以#结束):\n");
fflush(stdin);
scanf("%c",&data);
while(data!='#'){
L.length++;
setdata(L,data);
scanf("%c",&data);
}
appear(L);
printf("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n\n");
printf("请输入您想开始比较的位置\n");
scanf("%d",&location);
printf("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n\n");
int www = bfsuan(S,L,location);
if(www)
printf("主串内含有副串,位置为:%d\n",www);
else
printf("主串内无副串。\n");
}
正规BF算法
int BF(sstring S,sstring T,int location){
int = lication;
j=1;
while(i<=S.length && j<=T.length){
if(S.ch[i] == T.ch[j]){
i++;
j++;
}
else{
i=i-j+2;
j=1;
}
if(j>T.length)
return i-T.length;
else
return 0;
}
}