BF算法
#include<iostream> //输入字符串用gets函数,故i,j从0开始
#include<cstring>
#define OK 1
#define ERROR -1
#define Status int
#define MAXSIZE 255
using namespace std;
typedef struct //定长存储
{
char ch[MAXSIZE+1]; //存储串的一维数组
int length; //串的当前长度
}SString;
//BF算法
int Index_BF(SString S,SString T,int pos)
{//返回模式T在主串S中第pos个字符开始第一次出现的位置。若不存在,则返回值为0.
//其中,T非空,0<=pos<S.length
int i=pos;
int j=0; //初始化
while(i<S.length && j<T.length ) //两个串均未比较到串尾
{
if( S.ch [i] == T.ch [j] ) //继续比较后继字符
{
++i;
++j;
}
else //指针后退开始重新匹配
{
i=i-j+1;
j=0;
}
}
if(j+1>T.length ) //匹配成功
return i-T.length+1 ;
else //匹配失败
return 0;
}
int main()
{
int pos=-1;
int n1,n2;
SString S,T;
cout<<"\t\t\t请输入字符串S: ";
gets(S.ch );
cout<<"\t\t\t请输入字符串T: ";
gets(T.ch );
cout<<endl;
S.length =strlen(S.ch );
T.length =strlen(T.ch );
//cout<<S.length <<" and "<<T.length <<endl;
for(int i=0; i<S.length ; i++)
{
if(S.ch [i] == T.ch [0])
{
pos = i;
break;
}
}
cout<<"\t\t*——————————————————————————————————————————*"<<endl;
cout<<"\t\t| 若不匹配输出0,否则输出和模式T中第pos(1<=pos<=T.length)个字符在主串S中的序号 |"<<endl;
cout<<"\t\t*——————————————————————————————————————————*"<<endl<<endl;
if(pos == -1)
{
cout<<"\t\t\t匹配结果:0"<<endl;
}
else
{
cout<<"\t\t\t匹配结果:"<<Index_BF( S, T, pos);
}
return 0;
}
KMP算法
#include<iostream> //输入字符串用gets函数,故i,j及next[]从0开始
#include<cstring>
#define OK 1
#define ERROR -1
#define OVERFLOW -1
#define Status int
#define MAXSIZE 255
using namespace std;
int next[255];
int nextval[255];
typedef struct //定长存储
{
char ch[MAXSIZE+1]; //存储串的一维数组
int length; //串的当前长度
}SString;
//KMP算法
int Index_KMP(SString S, SString T, int pos)
{
int i = pos, j = 0;
while (i < S.length && j < T.length) //两个串均未比较到串尾
{
if (j == -1 || S.ch[i] == T.ch[j]) //继续比较后继字符
{
++i;
++j;
}
else //模式串向右移动
j = next[j];
// j = nextval[j]; //next修正值
}
if (j+1 > T.length) //匹配成功
return i - T.length+1 ;
else
return 0; //匹配失败
}
void get_next(SString T)
{//求模式串T的next函数值并存入数组next
int i=0,j=0;
next[0]=-1;
j=next[i];
while(i<T.length )
{
if(j==-1 || T.ch[i]==T.ch[j])
{
++i;
++j;
next[i]=j;
}
else
j=next[j];
}
}
// next修正值
/*
void get_nextval(SString T)
{//求模式串T的next函数值并存入数组next
int i=0,j=0;
nextval[0]=-1;
j=nextval[i];
while(i<T.length )
{
if(j==-1 || T.ch[i]==T.ch[j])
{
++i;
++j;
if(T.ch[i]!=T.ch[j])
nextval[i]=j;
else
nextval[i]=nextval[j];
}
else
j=nextval[j];
}
}
*/
int main()
{
int pos=-1;
int n1,n2;
SString S,T;
cout<<"\t\t\t请输入字符串S: ";
gets(S.ch );
cout<<"\t\t\t请输入字符串T: ";
gets(T.ch );
cout<<endl;
S.length = strlen( S.ch );
T.length = strlen( T.ch );
//cout<<S.length <<" and "<<T.length <<endl;
for(int i=0; i<S.length ; i++)
{
if(S.ch [i] == T.ch [0])
{
pos = i;
break;
}
}
cout<<"\t\t*——————————————————————————————————————————*"<<endl;
cout<<"\t\t| 若不匹配输出0,否则输出和模式T中第pos(1<=pos<=T.length)个字符在主串S中的序号 |"<<endl;
cout<<"\t\t*——————————————————————————————————————————*"<<endl;
cout<<endl;
get_next( T );
// get_nextval( T ); //next修正值
if(pos == -1)
{
cout<<"\t\t\t匹配结果:0"<<endl;
}
else
{
cout<<"\t\t\t匹配结果:"<<Index_KMP( S, T, pos );
}
return 0;
}