朴素的匹配算法:
#include<iostream>
#include<string>
using namespace std;
void Match(string longstr,string shortstr)
{
string::iterator i,j,temp;
i=longstr.begin();
temp=i;
j=shortstr.begin();
while(i!=longstr.end()&&j!=shortstr.end())
{
if(*i==*j)
{
++i;
++j;
}
else{
++temp;
i=temp;
j=shortstr.begin();
}
}
if(j==shortstr.end())
cout<<"匹配"<<endl;
else
cout<<"不匹配"<<endl;
return 0;
}
KMP算法:
#include<iostream>
#include<string>
using namespace std;
void getNext(string shortstr,int *next)
{
int j,k;
next[0]=-1;
j=0;
k=-1;
while(j<shortstr.size())
{
if(k==-1||shortstr[j]==shortstr[k]) //匹配的情况下,shortstr[j]==shortstr[k]
{
j++;
k++;
next[j]=k;
}
else //shortstr[j]!=shortstr[k]
k=next[k];
}
}
int KMPMatch(string longstr,string shortstr)
{
int next[100];
int i,j;
i=0;
j=0;
getNext(shortstr,next);
while(i<longstr.size())
{
if(j==-1||longstr[i]==shortstr[j])
{
i++;
j++;
}
else
{
j=next[j]; //消除了指针i的回溯
}
if(j==shortstr.size())
return i-shortstr.size();//返回匹配的初始下标
}
return -1;
}