KMP算法
#include <iostream>#include <vector>
#include <string>
using namespace std;
const int INF=0x7fff;
int p[INF];
//ababacb
//
void findB(string str)
{
int len=str.length();
string strcopy(len+1,0);
strcopy[0]='0';
for (int i=0;i<len;i++)
{
strcopy[i+1]=str[i];
}
p[0]=0;
p[1]=0;
for (int i=2;i<=len;i++)
{
int k=i-1;
while(strcopy[i]!=strcopy[p[k]+1])
{
k=p[p[k]];
if (k==0)
{
break;
}
}
if (k==0)
{
p[i]=0;
}
else
{
p[i]=p[k]+1;
}
}
cout<<strcopy<<endl;
for (int i=1;i<=len;i++)
{
cout<<p[i]<<endl;
}
}
//string strb="ababacb";
//string stra="abababaabab";
int KMP(string strb,string stra)
{
int lena=stra.length();
int lenb=strb.length();
string strcb(lenb+2,'x');
string strca(lena+2,'x');
for (int i=0;i<lena;i++)
{
strca[i+1]=stra[i];
}
for (int i=0;i<lenb;i++)
{
strcb[i+1]=strb[i];
}
int i=1,j=1;
bool flag=false;
int index=0;
cout<<strca<<endl;
cout<<strcb<<endl;
bool flag1=true;
for(i=1;i<=lena&&flag1;)
{
while (strca[i]==strcb[j]&&j<=lenb)
{
i++;
j++;
if (i>lena)
{
flag1=false;
break;
}
}
if (j>lenb)
{
flag=true;
index=i-j+1;
break;
}
i--;
j--;
j=p[j];
if (j==0)
{
i++;
while(strca[i]!=strcb[1]&&flag1)
{
i++;
if (i>lena)
{
flag1=false;
break;
}
}
j=1;
}
}
return index;
}
int main()
{
string strb="ababacb";
string stra="abababaababacb";
string testb="abdbay";
string testa="ddabdddabdbac";
findB(testb);
int x=KMP(testb,testa);
cout<<x<<endl;
}