/*
* 建立模式串p的next数组
* next数组与子串公共前后缀长度有关
*/
void getNext(char * p, int * next)
{
next[0] = -1;
//j相当于KMP时当前扫描位置所要新对齐的下标
int i = 0, j = -1;
while (i < strlen(p))
{
if (j == -1 || p[i] == p[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
int KMP(char * t, char * p)
{
//t原串,p子串
int i = 0;
int j = 0;
//扫描
while (i < strlen(t) && j < strlen(p))
{
if (j == -1 || t[i] == p[j])
{
i++;j++;
}
else
//子串改变起始位置
j = next[j];
}
//匹配的开始处
if (j == strlen(p))
return i - j;
else
//不存在匹配的
return -1;
}
视频讲解:
KMP匹配算法1