KMP模板与讲解

读书笔记终于写完了,写一下我对KMP的理解。

KMP的思想就是尽量利用已经得到的信息,来降低时间复杂度,已经得到的信息存放在next数组里。算法确实很难理解,所以很难讲解。。举个例子来说吧。

设字符串是str[],next[5] = 2。

就表示str[5]前面的2个字符,与str[2]前面的2个字符相同,也就是str[0] == str[3], str[1] == str[4],这样把str[2]平移到str[5]的位置以后,就能保证前面的已经匹配了。就是下图:

目标串    ..........a  b  c.........

str[]   a  b  c  a  b  d  e  f

下标    0  1  2  3  4  5  6  7

这时候在下标为5的位置,d和c是不匹配的,因为next[5] = 2,所以把下标为2的c平移到下标为5的位置,再次比较。

目标串    ..........a  b  c.........

            str[]              a  b  c  a  b  d  e  f

下标    0  1  2  3  4  5  6  7

当下标超出待匹配的字符串的长度时,就说明在目标串中找到了该字串。

这里还有一个定理:next数组中的值就是"前缀"和"后缀"的最长的共有元素的长度。

还有一句“名言”:假如你要向你喜欢的人表白的话,我的名字是你的告白语中的子串吗?

最后是几篇比较好的讲解KMP的文章,讲解方式各不相同,但是都讲得特别好。

http://www.matrix67.com/blog/archives/115

http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html

http://blog.csdn.net/v_july_v/article/details/7041827

 1 void kmp(char target[], char source[])
 2 {
 3     int n = strlen(target);
 4     int m = strlen(source);
 5     int *next = new int[m];
 6     int j = -1;
 7     next[0] = -1;
 8     for(int i = 1; i < m; i++)
 9     {
10         while(j >= 0 && source[j+1] != source[i])
11             j = next[j];
12         if(source[j+1] == source[i])
13             j++;
14         next[i] = j;
15     }
16     j = -1;
17     for(int i = 0; i < n; i++)
18     {
19         while(j >= 0 && source[j+1] != target[i])
20             j = next[j];
21         if(source[j+1] == target[i])
22             j++;
23         if(j >= m-1)
24         {
25             printf("%d
", i-m+1);
26             j = next[j]; //继续查找更多
27             //return;   //不再继续查找
28         }
29     }
30 }
View Code
原文地址:https://www.cnblogs.com/wolfred7464/p/3414993.html