KMP算法是一种模式匹配算法,以前早期的字符串匹配算法是一种简单的朴素匹配算法。附上代码:
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
//得到next数组
void Get_KMP_NEXT(int next[],string str_suit)
{
int i=1;
int j=0;
next[1]=0;
while(i<str_suit.length())
{
if(j==0||str_suit[i]==str_suit[j])
{
i++;
j++;
next[i]=j;
}else{
j=next[j];
}
}
}
int KMP_index(string str_source,string str_suit,int next[])
{
int i=0;
int j=0;
while (i<str_source.length()&&j<str_suit.length())
{
if(j==0||str_source[i]==str_suit[j])
{
i++;
j++;
}else{
j=next[j];
}
}
if(j>=str_suit.length())
{
//说明已经找到了匹配全部的
return i-str_suit.length();
}else{
return 0;
}
}
void main()
{
string str_Source="ababcdefg";
string str_suit="cde";
int next[255];
Get_KMP_NEXT(next,str_suit);
int index=KMP_index(str_Source,str_suit,next);
printf("匹配结局是%d",index);
system("pause");
}