首页 > 其他 > 详细

KMP算法

时间:2014-04-03 20:12:56      阅读:501      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 1 // 根据算法引论一书中的说明写的程序
 2 #include <stdio.h>
 3 #include <string>
 4 #define MAX_N 1000
 5 using std::string;
 6 
 7 int next[MAX_N];
 8 
 9 void generate_next(const string& pattern) {
10     next[0] = -1;
11     for(int i = 1; i < pattern.length(); ++i) {
12         int j = next[i-1];
13         while (j >= 0 && pattern[j] != pattern[i-1])
14             j = next[j];
15 
16         // either pattern[j] == pattern[i-1] or j < 0
17         next[i] = ++j;
18     }
19 }
20 
21 void match(const string& text, const string& pattern) {
22     
23     generate_next(pattern);
24     for(int i = 0, j = 0; i < text.length(); ++i) {
25         while (j >= 0 && text[i] != pattern[j]) {
26             j = next[j];
27         }
28         // either text[i] = pattern[j] or j = -1
29         ++j;
30         if (pattern.length() == j) {
31             // get a match, this match starts from k in text
32             int k = i - j + 1;
33             printf("%s\n", text.substr(k).c_str());
34             // let j = 0 for next match
35             j = 0;
36         }
37     }
38 }
39 
40 int main() {
41     string t = "xyxxyxyxyyxyxyxyyxyxyxx", p = "xy";
42     match(t, p);
43 }
View Code

KMP算法,布布扣,bubuko.com

KMP算法

原文:http://www.cnblogs.com/lzonline01/p/3642139.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!