KMP算法

教你初步了解KMP算法

作者: July 、saturnma、上善若水。     时间; 二零一一年一月一日

-----------------------

本文参考:数据结构(c语言版) 李云清等编著、算法导论

引言:
在文本编辑中,我们经常要在一段文本中某个特定的位置找出 某个特定的字符或模式。
由此,便产生了字符串的匹配问题。
本文由简单的字符串匹配算法开始,再到KMP算法,由浅入深,教你从头到尾彻底理解KMP算法。

来看算法导论一书上关于此字符串问题的定义:
假设文本是一个长度为n的数组T[1...n],模式是一个长度为m<=n的数组P[1....m]。
进一步假设P和T的元素都是属于有限字母表Σ.中的字符。

依据上图,再来解释下字符串匹配问题。目标是找出所有在文本T=abcabaabcaabac中的模式P=abaa所有出现。
该模式仅在文本中出现了一次,在位移s=3处。位移s=3是有效位移。

第一节、简单的字符串匹配算法

简单的字符串匹配算法用一个循环来找出所有有效位移,
该循环对n-m+1个可能的每一个s值检查条件P[1....m]=T[s+1....s+m]。

NAIVE-STRING-MATCHER(T, P)
1 n ← length[T]
2 m ← length[P]
3 for s ← 0 to n - m
4     do if P[1 ‥ m] = T[s + 1 ‥ s + m]          
      //对n-m+1个可能的位移s中的每一个值,比较相应的字符的循环必须执行m次。
5           then print "Pattern occurs with shift" s

单字符串匹配算法,上图针对文本T=acaabc 和模式P=aab。
上述第4行代码,n-m+1个可能的位移s中的每一个值,比较相应的字符的循环必须执行m次。
所以,在最坏情况下,此简单模式匹配算法的运行时间为O((n-m+1)m)。

--------------------------------

下面我再来举个具体例子,并给出一具体运行程序:
对于目的字串target是banananobano,要匹配的字串pattern是nano,的情况,

下面是匹配过程,原理很简单,只要先和target字串的第一个字符比较,
如果相同就比较下一个,如果不同就把pattern右移一下,
之后再从pattern的每一个字符比较,这个算法的运行过程如下图。
//index表示的每n次匹配的情形。

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 int match(const string& target,const string& pattern)
 5 {
 6     int target_length = target.size();
 7     int pattern_length = pattern.size();
 8     int target_index = 0;
 9     int pattern_index = 0;
10     while(target_index < target_length && pattern_index < pattern_length)
11     {
12         if(target[target_index]==pattern[pattern_index])
13         {
14             ++target_index;
15             ++pattern_index;
16         }
17         else
18         {
19             target_index -= (pattern_index-1); 
20             pattern_index = 0;
21         }
22     }
23     if(pattern_index == pattern_length)
24     {
25         return target_index - pattern_length;
26     }
27     else
28     {
29         return -1;
30     }
31 }
32 int main()
33 {
34     cout<<match("banananobano","nano")<<endl;
35     return 0;
36 }

//运行结果为4。

上面的算法进间复杂度是O(pattern_length*target_length),
我们主要把时间浪费在什么地方呢,
观查index =2那一步,我们已经匹配了3个字符,而第4个字符是不匹配的,这时我们已经匹配的字符序列是nan,

此时如果向右移动一位,那么nan最先匹配的字符序列将是an,这肯定是不能匹配的,
之后再右移一位,匹配的是nan最先匹配的序列是n,这是可以匹配的。

如果我们事先知道pattern本身的这些信息就不用每次匹配失败后都把target_index回退回去,
这种回退就浪费了很多不必要的时间,如果能事先计算出pattern本身的这些性质,
那么就可以在失配时直接把pattern移动到下一个可能的位置,
把其中根本不可能匹配的过程省略掉,
如上表所示我们在index=2时失配,此时就可以直接把pattern移动到index=4的状态,
kmp算法就是从此出发。

第二节、KMP算法

2.1、 覆盖函数(overlay_function)

覆盖函数所表征的是pattern本身的性质,可以让为其表征的是pattern从左开始的所有连续子串的自我覆盖程度。
比如如下的字串,abaabcaba

由于计数是从0始的,因此覆盖函数的值为0说明有1个匹配,对于从0还是从来开始计数是偏好问题,

具体请自行调整,其中-1表示没有覆盖,那么何为覆盖呢,下面比较数学的来看一下定义,比如对于序列

a0a1...aj-1 aj

要找到一个k,使它满足

a0a1...ak-1ak=aj-kaj-k+1...aj-1aj

而没有更大的k满足这个条件,就是说要找到尽可能大k,使pattern前k字符与后k字符相匹配,k要尽可能的大,
原因是如果有比较大的k存在,而我们选择较小的满足条件的k,
那么当失配时,我们就会使pattern向右移动的位置变大,而较少的移动位置是存在匹配的,这样我们就会把可能匹配的结果丢失。

比如下面的序列,

在红色部分失配,正确的结果是k=1的情况,把pattern右移4位,如果选择k=0,右移5位则会产生错误。
计算这个overlay函数的方法可以采用递推,可以想象如果对于pattern的前j个字符,如果覆盖函数值为k

a0a1...ak-1ak=aj-kaj-k+1...aj-1aj
则对于pattern的前j+1序列字符,则有如下可能
⑴     pattern[k+1]==pattern[j+1] 此时overlay(j+1)=k+1=overlay(j)+1
⑵     pattern[k+1]≠pattern[j+1] 此时只能在pattern前k+1个子符组所的子串中找到相应的overlay函数,h=overlay(k),如果此时pattern[h+1]==pattern[j+1],则overlay(j+1)=h+1否则重复(2)过程.

下面给出一段计算覆盖函数的代码:

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 void compute_overlay(const string& pattern)
 5 {
 6     const int pattern_length = pattern.size();
 7     int *overlay_function = new int[pattern_length];
 8     int index;
 9     overlay_function[0] = -1;
10     for(int i=1;i<pattern_length;++i)
11     {
12         index = overlay_function[i-1];
13         //store previous fail position k to index;
14         
15         while(index>=0 && pattern[i]!=pattern[index+1])
16         {
17             index = overlay_function[index];
18         }
19         if(pattern[i]==pattern[index+1])
20         {
21             overlay_function[i] = index + 1;  
22         }
23         else
24         {
25             overlay_function[i] = -1;
26         }
27     }
28     for(i=0;i<pattern_length;++i)
29     {
30         cout<<overlay_function[i]<<endl;
31     }
32     delete[] overlay_function;
33 }
34 int main()
35 {
36     string pattern = "abaabcaba";
37     compute_overlay(pattern);
38     return 0;
39 }

运行结果为:

-1
-1
0
0
1
-1
0
1
2
Press any key to continue

-------------------------------------

2.2、kmp算法
     有了覆盖函数,那么实现kmp算法就是很简单的了,我们的原则还是从左向右匹配,但是当失配发生时,我们不用把target_index向回移动,target_index前面已经匹配过的部分在pattern自身就能体现出来,只要动pattern_index就可以了。

当发生在j长度失配时,只要把pattern向右移动j-overlay(j)长度就可以了。

如果失配时pattern_index==0,相当于pattern第一个字符就不匹配,
这时就应该把target_index加1,向右移动1位就可以了。

ok,下图就是KMP算法的过程(红色即是采用KMP算法的执行过程):

另一作者saturnman发现,在上述KMP匹配过程图中,index=8和index=11处画错了。还有,anaven也早已发现,index=3处也画错了。非常感谢。但图已无法修改,见谅。

KMP 算法可在O(n+m)时间内完成全部的串的模式匹配工作。

ok,最后给出KMP算法实现的c++代码:

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 using namespace std;
 5 int kmp_find(const string& target,const string& pattern)
 6 {
 7     const int target_length = target.size();
 8     const int pattern_length = pattern.size();
 9     int * overlay_value = new int[pattern_length];
10     overlay_value[0] = -1;
11     int index = 0;
12     for(int i=1;i<pattern_length;++i)
13     {
14         index = overlay_value[i-1];
15         while(index>=0 && pattern[index+1]!=pattern[i])
16         {
17             index  = overlay_value[index];
18         }
19         if(pattern[index+1]==pattern[i])
20         {
21             overlay_value[i] = index +1;
22         }
23         else
24         {
25             overlay_value[i] = -1;
26         }
27     }
28     //match algorithm start
29     int pattern_index = 0;
30     int target_index = 0;
31     while(pattern_index<pattern_length&&target_index<target_length)
32     {
33         if(target[target_index]==pattern[pattern_index])
34         {
35             ++target_index;
36             ++pattern_index;
37         }
38         else if(pattern_index==0)
39         {
40             ++target_index;
41         }
42         else
43         {
44             pattern_index = overlay_value[pattern_index-1]+1;
45         }
46     }
47     if(pattern_index==pattern_length)
48     {
49         return target_index-pattern_index;
50     }
51     else
52     {
53         return -1;
54     }
55     delete [] overlay_value;
56 }
57 int main()
58 {
59     string source = " annbcdanacadsannannabnna";
60     string pattern = " annacanna";
61     cout<<kmp_find(source,pattern)<<endl;
62     return 0;
63 }

//运行结果为 -1.

posted @ 2012-11-06 15:54  legendmaner  阅读(166)  评论(0)    收藏  举报