關鍵在於模式串的next數組
#include <iostream>
using namespace std;
void Next(char *p, int next[]);
int main()
{
char SS[100];
int next[101];
char TT[100];
cout<<"輸入源串:"<<endl;
cin>>SS;
cout<<"輸入模式串:"<<endl;
cin>>TT;
Next(TT,next);
cout<<"模式串的next數組值:"<<endl;
int length=strlen(TT);
for(int i=1;i<=length;i++)
{
cout<<next[i]<<" ";
}
cout<<endl;
//------------------------------------------匹配
bool equal=false;
int x=0;
int y=0;
int s_len=strlen(SS);
int t_len=strlen(TT);
while(/*y<t_len && x<=(s_len-t_len)*/x<s_len)
{
if(TT[y]==SS[x])
{
x++;
y++;
}
else
{
if(next[y+1]==1)
y=0;
else if(next[y+1]==0)
x++;
}
if(y==t_len)
{
cout<<"從第"<<(x-y+1)<<"個字母起到"<<(x-y+t_len)<<"個字母匹配成功"<<endl;
equal=true;
y=0;
}
}
if(!equal)
cout<<"無匹配成功的"<<endl;
}
void Next(char *p, int next[])
{
int i=1,j=0;
next[1]=0;
int length=strlen(p);
while(i<=length+1)
{
if(j==0 || p[i]==p[j])
{
++i;
++j;
next[i]=j;
}
else
j=next[j];
}
}