Problem B Oulipo(KMP基础)

题目大意:

  给你一个模式串和一个文本串,问你模式串在文本串中出现的次数,可能出现重叠的情况。

代码:

 1 # include<cstdio>
 2 # include<iostream>
 3 # include<cstring>
 4 
 5 using namespace std;
 6 
 7 char s2[10004];
 8 char s1[1000004];
 9 int nxt[10004];
10 
11 void get_next()
12 {
13     int t1 = 0,t2;
14     t2 = nxt[0] = -1;
15     int len = strlen(s2);
16     while ( t1<len )
17     {
18         if ( t2==-1||s2[t2]==s2[t1] )
19         {
20             t1++;t2++;
21             nxt[t1] = t2;
22         }
23         else
24             t2 = nxt[t2];
25     }
26 }
27 
28 int kmp ( char *s1, char *s2 )
29 {
30     int len1 = strlen(s1), len2 = strlen(s2);
31     int t1 = 0,t2 = 0;
32     int times = 0;
33     while ( t1 < len1 )
34     {
35         if ( t2==-1||s1[t1]==s2[t2] )
36         {
37             t1++;t2++;
38         }
39         else
40             t2 = nxt[t2];
41         if ( t2==len2 )
42         {
43             times+=1;
44             t2 = nxt[t2];
45         }
46     }
47     return times;
48 }
49 
50 
51 int main(void)
52 {
53     int t;scanf("%d",&t);
54     while ( t-- )
55     {
56         scanf("%s%s",s2,s1);
57         get_next();
58         int ans = kmp(s1,s2);
59         printf("%d
",ans);
60     }
61 
62 
63     return 0;
64 }
原文地址:https://www.cnblogs.com/wikioibai/p/4537481.html