#include <iostream>
using namespace std;
void originalMatch(char* o,char* m)
{
int original = strlen(o);
int match = strlen(m);
if (match > original||match ==0||original == 0)
{
cout<<"length is incorrect!"<<endl;
return;
}
bool haveornot = true;
for (auto i =0;i<original-match+1;i++)
{
bool flag = true;
for (auto j =0;j < match;j++)
{
if(o[i+j]!=m[j])
{
flag =false;
break;
}
}
if (flag)
{
haveornot =false;
cout<<"find the match string,the place is "<<i+1<<endl;
}
}
if (haveornot)
{
cout<<"there is no string \""<<m<<"\" in the string \""<<o<<"\"!"<<endl;
}
}
void Kmp(char* o,char* m)
{
int original = strlen(o);
int match = strlen(m);
if (match > original||match ==0||original == 0)
{
cout<<"length is incorrect!"<<endl;
return;
}
int* a =new int[match];
int q = 0;
a[0] = 0;
bool haveornot = true;
for (auto i =1;i<match;i++)
{
while(q>0&&m[q]!=m[i])
q = a[q];
if (m[q] == m[i])
q++;
a[i] = q;
}
q=0;
for (auto i =0;i<original;i++)
{
while(q>0&&m[q]!=o[i])
q = a[q-1];//減一是爲了保證前面已匹配的 向右移動的位數,q加1表示匹配位置,運行到這時q表示匹配不成功所以移動前面的
if (m[q] == o[i])
q++;
if (q == match)
{
haveornot =false;
cout<<"find the match string,the place is "<<(i-q+1)+1<<endl;
q=a[q-1];//保證匹配成功後面所要移動的位置
//此處不需要保證i的後移,因爲i後移了就會使成立m[q]!=o[i]
}
}
if (haveornot)
{
cout<<"there is no string \""<<m<<"\" in the string \""<<o<<"\"!"<<endl;
}
delete []a;
}
void main()
{
char o[100] = "anwsanwwqeasdfaanwsanwadadwanwsanwsanw";
char m[100] ="anwsanw";
originalMatch(o,m);
cout<<"kmp\n";
Kmp(o,m);
system("pause");
}
KMP算法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.