数据结构串的模式匹配本课件
- 格式:pdf
- 大小:2.13 MB
- 文档页数:19
数据结构一串的模式匹配实验一串的模式匹配1.程序设计简介为简化设计,程序直接利用C++字符数组作为串的存储结构。
程序提供显示串(包含主串和模式串)、计算Next[]、BF匹配、KMP匹配、重建主串、重建模式串等功能。
2.源代码〃串模式匹配的类定义Fin dSub.cpp#in cludevioma nip.h>#in cludevstri ng.h>#in clude<stdio.h>#in clude<stdlib.h>#in cludevstri ng>const maxsize=30;int In dexBF(char s[],char t[],i nt pos){int i,j,m, n;i=pos-1;j=0;m=strle n( s);n=strle n(t);while(i<m && j<n){if(s[i]==t[j]){++i;++j;}else {i=i-j+1;j=0;}}if(j>=n)return i-n+1;elsereturn -1;}void GetNext(char t[],i nt next[]){//求模式串T的next函数值并存入数组next in t j=0,k=-1;int n=strle n(t);n ext[j]=-1;while(j <n){if(k==-1||t[j]==t[k]){j++;k++; next[j]=k;}else k=n ext[k];}int IndexKMP(char s[],char t[],int next[],int pos){//利用模式串T的next函数求T在主串S中第pos个字符之后的位置的KMP算法。
// 其中,T 非空,1 < pos< StrLength(S) in t i,j, n;i=pos-1;j=0;int m=strle n( s);〃s[m]='\0:n=strle n(t);//t[ n]='\0:while(i<m && jvn)if(j==-1||s[i]==t[j]){i++;j++;}〃继续比较后继字符else j=next[j];//模式串向右移动if(j>=n) return i-n+1;// 匹配成功return -1;}〃串模式匹配的测试void mai n(){ char s[maxsize]="aaabaaaabaa",t[maxsize]="aaaab"int in dex,* nex t;int choice,j,pos=0;int m,n;m=strle n( s);n=strle n(t);n ext=new int[n];GetNext(t, next);do{//显示主菜单cout«"1-BF 匹配\n";cout«"2-KMP 匹配\n";cout<<"3-查看Next[]\n";cout<<"4-显示串\n";cout<<"6-退出\n";cout«"E nter choice:";cin> >choice;switch(choice){case 1://BF 匹配cout<<"输入匹配起始位置:"cin> >pos;if(pos<=m-n+1)coutvv"主串为:"vvs<v'\t'vv" 子串为:"vvtvvendl;cout«"BF 的结果:"<<endl;in dex=In dexBF(s,t,pos);if(in dex!=-1)cout<<"模式串t在主串s中的位置从第"<<index<<"个字符开始"<<endl;else cout<<"主串s中不含模式串t"<<e ndl;}else{ cout<<"位置非法,无法匹配!"<<e ndl; }break;case 2://KMP 算法cout<<"输入匹配起始位置:";cin> >pos;if(pos<=m-n+1){cout<<"主串为:"<<s<<'\t'<<" 子串为:"vvtvvendl;cout«"KMP 匹配结果:"<<endl;in dex=I ndexKMP(s,t, next,pos);if(in dex!=-1)cout<<"模式串在主串的位置从第"<<index<<"个字符开始"<<endl;elsecout<<"主串s中不含模式串t"<<e ndl;}else{ cout<<"位置非法,无法匹配!"<<e ndl; }break;case 3://显示NEXTcout<<"子串为:"<<t<<endl;for(j=0;j< n;j++){cout<<" next["<<j<<"]="<< next[j]<<'\t';if((j+1)%5==0) cout<<e ndl;}cout«e ndl; break;case 4: /湿示串cout«"主串为:"<<s;cout«"子串为:"<<t;cout«e ndl;break;case 6://退出cout«"结束运行!"<<endl; break;default:cout<v"lnvalid choice'n"; break;}}while(choice!=6);}3.程序运行结果:实验二求串中最长重复子串1•问题描述设串 S=”1s2 sn " , T= ”1t2 ......... tm ” 如果 rr + +\M^Dev^^Mytro ^1127 .De bug\201 i 1127A予禺为:aaaab 了 昌为=d4d4b next tl1-0 next[2J-l next(31-2 next[41-3ncm HIT %■11N ;"』”【 帥wJHT € S,则称T为S的子串。