kmp实操,分为strstr处理比较函数,和get_next处理next数组。
核心还是在于理解next数组,这里给没有匹配的next赋值-1,所以代码中需要有>0的判断。
next[j]记录的是到j为止,包括j,前后缀重复长度,所以应该应用于子串j+1的位置。
get_next
void get_next(int* next,string needle)
{
int j=-1;
next[0]=j;
for(int i=1;i<needle.size();++i)
{//分为前后缀 等和不等
while(j>=0&&needle[i]!=needle[j+1])
{
j=next[j];//回退
}
//因为如果是一段起头的比较,就应该让j从-1开始,
//而如果前面刚刚已经比较了一部分相同的,那么j不为-1,如果后面也是就继续,如果不是就回退
if(needle[i]==needle[j+1])
{
j++;
}
next[i]=j;
}
}
strstr
int strStr(string haystack, string needle) {
int l1=haystack.size();
int l2=needle.size();
if(l2==0)return 0;
vector<int> next(l2);
get_next(&next[0],needle);
int j=-1;//next里起始位置-1
for(int i=0;i<l1;++i)
{//实际上分两步,比较和校验结果
//比较分为等与不等
while(j>=0&&haystack[i]!=needle[j+1])
{
j=next[j];
}//i会在for里加
if(haystack[i]==needle[j+1])
{
j++;
}
if(j == (l2-1))
{
return (i-l2+1);//因为是起始所以+1
}
}
return -1;
}