KMP算法
复杂度O(m+n)
查找某个字符串是否被另一个字符串包含
原理可以见:
http://news.cnblogs.com/n/176771/
代码出自<<大话数据结构>>
#include <cstring>
#include <iostream>
using namespace std;
void getNext( char *T,int *next)
{
int i,j;
i=1;
j=0;
next[1]=0;
while(i<strlen(T))
{
if(j==0 || T[i]==T[j])
{
i++;
j++;
next[i]=j;
}
else
{
j=next[j];
}
}
}
void getNextVar( char *T,int *next)
{
int i,j;
i=1;
j=0;
next[1]=0;
while(i<strlen(T))
{
if(j==0 || T[i]==T[j])
{
i++;
j++;
if(T[i]!=T[j])
next[i]=j;
else
next[i]=next[j];
}
else
{
j=next[j];
}
}
}
int index_kmp(char *S,char *T,int pos)
{
int i=pos;
int j=1;
int next[255];
//getNext(T,next);
getNextVar(T,next);
while(i<=S[0] && j<=T[0])
{
if(j==0 || S[i]==T[j])
{
++i;
++j;
}
else
{
j=next[j];
}
}
if(j>T[0])
return i-T[0];
else
return 0;
}
int main()
{
char S[20]="-aaaaaaax";
char T[10]="-ax";
S[0]=(char)8; //第0位存放在字符串长度
T[0]=(char)2;
cout << index_kmp(S,T,1) << endl;;
}