码迷,mamicode.com
首页 > 其他好文 > 详细

第一轮复习完毕,kmp走起

时间:2016-06-28 23:30:04      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:

//代码via:http://blog.csdn.net/v_JULY_v/article/details/6111565

//简单思路via:http://study.163.com/course/courseLearn.htm?courseId=468002#/learn/video?lessonId=1024414&courseId=468002

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

相比BF算法(暴力匹配)KMP算法的时间复杂度有所提升,尤其是处理无重复匹配串。

但是我们除了目标串与匹配串还需引入一个数组int next[];存放每次失配位置将回溯(?回那一位继续进行kmp匹配

如何获得next[]数组是一个关键。

代码之前先谈谈思路

1)如果匹配串没有重复,那么一切好说,next[]按脚标顺序即可

2)匹配串有重复的情况,这就是我们要讨论的重点了,下一次从匹配串的哪一位开始与适配位置所在的目标串元素进行比较?

    这个位置就是我们next[i]所对应的值

    a.

target k m p k k m p m p k
string 0 1 2 3 4 5 6 7 8 9

 

compare 0 1 2 3 4
string k m p m p

 

 

next 0 1 2 3 4
int 0 0 0 2 3

 

第一轮复习完毕,kmp走起

标签:

原文地址:http://www.cnblogs.com/yuelien/p/5625287.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!