数据结构 模式匹配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];}}
相关文章推荐
- 数据结构- 串的模式匹配算法:BF和 KMP算法
- 数据结构- 串的模式匹配算法:BF和 KMP算法
- 数据结构第四次上机 第四章之BF和KMP算法(顺序串的各种模式匹配算法)
- 数据结构_串_串的模式匹配_KMP算法_C++实现
- 数据结构- 串的模式匹配算法:BF和 KMP算法
- 数据结构- 串的模式匹配算法:BF和 KMP算法
- 数据结构Java实现——③串--->串的模式匹配:Brute-Force算法和 KMP算法
- 数据结构- 串的模式匹配算法:BF和 KMP算法
- 数据结构_串_串的模式匹配_KMP/BF
- 对比了一下数据结构上的朴素模式匹配(Brute Force)和KMP算法
- 字符串模式匹配之KMP算法图解与 next 数组原理和实现方案
- 模式匹配KMP算法实现
- 模式匹配之(BF KMP算法)
- 《数据结构》之串的模式匹配算法——KMP算法
- 字符串模式匹配算法1 - BF和KMP算法
- 数据结构(11)--串的模式匹配算法之BF、KMP算法
- 查表:字符串模式匹配(BF、KMP算法)
- 字符串模式匹配中BF算法和KMP算法的java实现
- KMP算法实现字符串的模式匹配完整C代码
- 字符串模式匹配算法--BF & KMP算法