/**KMP模式匹配 2015.03.17
***
*******/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int const MAX =10;
int GetNext(string & pattern ,int (&next)[MAX])// c语言中可以传递一个数组指针
{
int length = pattern.size();
int j = 0;//模式串的后缀
int k = -1;//模式串的前缀
next[0] = -1;//next数组首元素赋值为-1;
while (j < length-1)
{
if (k==-1 || pattern[k] == pattern[j])
{
++k;
++j;
next[j] = k;
}
else
k = next[k];
}
return 0;
}
int kmp_match(string & text,string & pattern,int next[])
{
int i=0;
int j=0;
int length_text = text.size();
int length_pattern = pattern.size();
while (i < length_text && j < length_pattern)
{
if (j==-1 || text[i]==pattern[j])
{
++i;
++j;
}
else
j = next[j];
}
if (j == length_pattern)
{
return i-j;
}
else
return -1;
}
int main()
{
string text = "abcdcdgabcaad";
string pattern = "abca";
int next[MAX] ={ };
GetNext(pattern,next);
cout<<"text is : "<<text<<endl;
cout<<"pattern is :"<<pattern<<endl;
cout<<"模式匹配的位置在 :"<<ends;
cout<<kmp_match(text,pattern,next)<<endl;
return 0;
}
11-03
3万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)