朴素的匹配算法:
#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]