sub[ ]代表子串,str[ ]代表原串,next[ ]代表当sub[i] != str[j]时,子串需要跳到的地方,实现代码如下:
获取next数组的代码:
void GetNext()//求子串中的相同的真前缀和真后缀
{
memset(next, 0, sizeof(next));
next[0] = -1;
int i = 0,j = -1;
int sub_len = strlen(sub);
while(i < sub_len)
{
if(j == -1 || sub[i] == sub[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}
KMP实现的代码:
int KMP()
{
int res = 0;
int sub_len = strlen(sub);
int str_len = strlen(str);
int i = 0;
int j = 0;
while(i < str_len && j < sub_len)
{
if(j == -1 || str[i] == sub[j])
{
i++;
j++;
}
else
j = next[j];
if(j == sub_len) //此处实现的是统计子串在原串中出现的次数
{ //这里可以根据具体情况来调整
res++;
j = next[j];
}
}
return res;
}
练习题:Oulipo-Poj