•参考资料

  [1]:KMP学习资料:左神进阶班第一节 

 

KMP学习小结

•KMP的用途

  对于给定的两个串 S,T,如何在线性时间内判断 S 是否包含 T 呢?

  以下默认 S,T 下标从 0 开始;

•前置知识

  $next$ 数组,定义 $next_i$ 表示 T 中前 i 个字符 ($T_0,T_1,\cdots ,T_{i-1}$) 最长前缀和最长后缀的匹配长度并且满足 $next_i < i$;

  并人为规定 $next_0=-1,next_1=0$;

  例如,假设 $T="aaaab"$,$next$ 求解情况如下:

    $\begin{aligned} next_0 &= -1 \\ next_1 &= 0 \\next_2 &=1\ (prefix="a",suffix="a") \\ next_3&=2\ (prefix="aa",suffix="aa")\\ next_4&=3\ (prefix="aaa",suffix="aaa") \\ next_5&=0\ (don't\ exsits\ prefix = suffix)\end{aligned}$;

  $next$ 数组的求解可以通过动态规划在线性时间内完成;

KMP && KMP求字符串循环节
 1 int next[maxn];
 2 void getNext(const char *s)
 3 {
 4     int len=strlen(s);
 5     next[0]=-1;
 6     next[1]=0;
 7     int index=2;
 8     int cnt=0;
 9     while(index <= len)
10     {
11         if(s[index-1] == s[cnt])
12             next[index++]=++cnt;
13         else if(cnt != 0)
14             cnt=next[cnt];
15         else
16             next[index++]=0;
17     }
18 }
next求解

相关文章: