'''KMP算法'''
//模式串匹配
比较指针前面是匹配的
求其最长公共前后缀
模式串移动到后缀所在的位置得到上下匹配
//求解next数组 next[j] = t
//j = t, next[j+1] = t+1 = next[j]+1
//j != t,
void getNext(Str substr, int next[])
{
int j = 1, t;
next[1] = 0;//数组第一位的特殊标记
while(j < substr.length)//长度小于模式串
{
if(t == 0 || substr.ch[j] == substr.ch[t])//j = t
{
next[j+1] = t+1;
++t;
++j;
}
else
t = next[t];//将t循环赋值给next,直到t = 0(next[j+1] = 1)或者j = t
}
}
//kmp算法
int KMP(Str str, Str substr, int next[])
{
int i = 1, j = 1;
while(i <= str.length && j <= substr.length)
{
if(j == 0 || str.ch[i] == substr.ch[j])
{
++i;
++j;
}
else
{
j = next[j];
}
if (j > substr.length)
return i-substr.length;
else
return 0;
}
}
//改进KMP
//升级为nextval数组,比较足迹
//求解nextval数组
j = 1时, nextval[j] = 0,特殊标记
j > 1时,Pj != Pnext[j], nextval[j] == next[j];
Pj == Pnext[j], nextval[j] == nextval[next[j]]
void getNextvalMid(Str substr, int nextval[], int next[])
{
int j = 1, t = 0;
next[1] = 0;//数组第一位的特殊标记
nextval[1] = 0;
while(j < substr.length)//长度小于模式串
{
if(t == 0 || substr.ch[j] == substr.ch[t])//j = t
{
next[j+1] = t+1;
if(substr.ch[j+1] != substr.ch[next[j+1]])
nextval[j+1] = next[j+1];
else
nextval[j+1] = nextval[next[j+1]];
++t;
++j;
}
else
t = nextval[t];//将t循环赋值给next,直到t = 0(next[j+1] = 1)或者j = t
}
}
//改进,扔掉next数组
void getNextval(Str substr, int nextval[])
{
int j = 1, t = 0;
nextval[1] = 0;
while(j < substr.length)//长度小于模式串
{
if(t == 0 || substr.ch[j] == substr.ch[t])//j = t
{
if(substr.ch[j+1] != substr.ch[t+1])
nextval[j+1] = t+1;
else
nextval[j+1] = nextval[t+1];
++t;
++j;
}
else
t = nextval[t];//将t循环赋值给next,直到t = 0(next[j+1] = 1)或者j = t
}
}