您的位置:首页 > 理论基础 > 数据结构算法

数据结构 模式匹配BF和KMP算法实现

2016-10-15 17:48 232 查看
BF 算法:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MaxSize 100 //串的最大长度
//串的定长顺序储存结构
typedef struct//
{
char str[MaxSize];//储存串的一维数组
}SString;
int BFIndex(SString S, int pos, SString T)
{
int i = pos;
int j = 0; //初始化
while(i <=strlen(S.str)&& j<=strlen(T.str)) //两串均未达到串尾
{
if(S.str[i-1] == T.str[j])//继续比较后续字符
{
i++;
j++;
}
else   //指针后退重新开始匹配
{
i = i-j+1;
j = 0;
}
}
if (j==strlen(T.str))//匹配成功
{
return (i-strlen(T.str));
}
else    //匹配失败
return 0;
}

int main()
{
SString S,T;
int pos,ans;
printf("请输入主串S的字符:");
scanf("%s",S.str);
printf("请输入子串T的字符:");
scanf("%s",T.str);
printf("请输入pos的值:");
scanf("%d",&pos);
ans=BFIndex(S,pos,T);//调用BFIndex函数
printf("子串T在主串S中第pos个字符之后的位置为:");
printf("%d\n",ans);
system("pause");
return 0;
}
KMP算法#include<stdio.h>#include<malloc.h>#include<stdlib.h>#include<string.h>#define MAXLEN 100//串的最大长度typedef struct{char ch[MAXLEN+1];}SString;void get_next(SString T,int next[])//求模式串next函数值 并存入数组next{int i,j;i=1;next[1]=0;j=0;while(i<strlen(T.ch)){if(j==0||T.ch[i]==T.ch[j]){++i;++j;next[i]=j;}elsej=next[j];}}int Index_KMP(SString S,SString T,int pos,int next[])//利用模式串T的next函数求T在主串S中第pos个字符之后的位置 ,其中T非空{int i,j;i=pos;j=1;while(i<=strlen(S.ch)&&j<=strlen(S.ch)){if(j==0||S.ch[i]==T.ch[j]){++i;++j;}else{j=next[j];}}if(j>strlen(T.ch))return i-strlen(T.ch);elsereturn 0;}int main(){SString S,T;int pos,ans,next[MAXLEN];printf("请输入S串\n");scanf("%s",S.ch);printf("请输入T串\n");scanf("%s",T.ch);printf("请输入pos的值\n");scanf("%d",&pos);get_next(T,next);ans=Index_KMP(S,T,pos,next);if(ans==0)printf("匹配失败\n");else{printf("模式T在主串S中第pos个字符开始第一次出现的位置为:%d\n",ans);}}KMP扩展:void get_nexttval(SString T,int nextval()){int i,j;i=1;nextval[1]=0;j=0;while(i<T.length){if(j==0||T.ch[i]==T.ch[j]){++i;++j;if(T.ch[i]!=T.ch[j])nextval[i]=j;else nextval[i]=nextval[j];}elsej=nextval[j];}}
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: