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

KMP模式匹配

时间:2015-05-16 18:04:51      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

KMP的具体算法讲解可以参考此博文

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

KMP算法的应用

http://poj.org/problem?id=2406

首先求得next数组

若基础字符串为t,输入字符串为s,若s=t^n;那么下面的等式必然满足

next(strlen(s)) = strlen(s)-strlen(t);

同时n = strlen(s)/strlen(t),此时必须满足strlen(s) % strlen(t) == 0

否则 n=1

技术分享
 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 using namespace std;
 5 
 6 const int N = 1000001;
 7 char s[N];
 8 int  _next[N];
 9 
10 void getNext()
11 {
12     int k,j;
13     k = -1;
14     j = 0;
15     _next[0] = -1;
16     int len = strlen(s);
17 
18     while(j < len)
19     {
20         if(s[k] == s[j] || k == -1)
21         {
22             k++;
23             j++;
24             _next[j] = k;
25         }
26         else
27         {
28             k = _next[k];
29         }
30     }
31 }
32 
33 int main()
34 {
35     while(scanf("%s", s))
36     {
37         if(strcmp(s, ".") == 0)
38         {
39             break;
40         }
41         memset(_next, 0, sizeof(_next));
42         int len = strlen(s);
43         getNext();
44 
45         int t = len - _next[len];
46         int res;
47 
48         if(len % t == 0)
49         {
50             res = len / t;
51         }
52         else
53         {
54             res = 1;
55         }
56         cout<<res<<endl;
57     }
58     return 0;
59 }
View Code

http://poj.org/problem?id=1961

与上一题类似

技术分享
 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 const int N = 1000001;
 7 int _next[N];
 8 char s[N];
 9 int n;
10 
11 void getNext()
12 {
13     int k,j;
14     k = -1;
15     j = 0;
16     _next[0] = -1;
17 
18     while(j < n)
19     {
20         if(s[k] == s[j] || k == -1)
21         {
22             k++;
23             j++;
24             _next[j] = k;
25         }
26         else
27         {
28             k = _next[k];
29         }
30     }
31 }
32 
33 int main()
34 {
35     int nCase = 0;
36     while(scanf("%d", &n) && n)
37     {
38         scanf("%s", s);
39 
40         nCase++;
41         memset(_next, 0, sizeof(_next));
42         getNext();
43 
44         printf("Test case #%d\n", nCase);
45         for(int i = 2; i <= n; i++)
46         {
47             if(_next[i] > 0)
48             {
49                 int ans = i - _next[i];
50                 if(i % ans == 0)
51                 {
52                     printf("%d %d\n", i, i/ans);
53                 }
54             }
55         }
56         printf("\n");
57     }
58 
59     return 0;
60 }
View Code

 

KMP模式匹配

标签:

原文地址:http://www.cnblogs.com/ygw0616/p/4508116.html

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