POJ 3461 Oulipo(模式串在主串中出现的次数)

题目链接:http://poj.org/problem?id=3461

题意:给你两个字符串word和text,求出word在text中出现的次数

思路:kmp算法的简单应用,遍历一遍text字符串即可,当前匹配的字符数达到word字符串的长度,即可确定word字符串出现一次了。

code:

 1 #include <cstdio>
 2 #include <cstring>
 3 using namespace std;
 4 const int MAXM = 10005;
 5 const int MAXN = 1000005;
 6 char word[MAXM];
 7 char text[MAXN];
 8 int next[MAXM];
 9 void GetNext()
10 {
11     int len = strlen(word);
12     int i = 0;
13     int j = -1;
14     next[0] = -1;
15     while (i < len)
16     {
17         if (-1 == j || word[i] == word[j]) next[++i] = ++j;
18         else j = next[j];
19     }
20 }
21 
22 int Kmp()
23 {
24     int i = 0;
25     int j = 0;
26     int ret = 0;
27     int tlen = strlen(text);
28     int wlen = strlen(word);
29     while (i < tlen)
30     {
31         if (-1 == j || text[i] == word[j])
32         {
33             ++i;
34             ++j;
35             if (j == wlen)
36             {
37                 ++ret;
38                 j = next[j];    // 已经匹配成功,重新定位j指向word中的位置
39             }
40         }
41         else j = next[j];     // 失配时,重新定位j指向word中的位置
42     }
43     return ret;
44 }
45 
46 int main()
47 {
48     int nCase;
49     scanf("%d", &nCase);
50     while (nCase--)
51     {
52         scanf("%s %s", word, text);
53         GetNext();
54         printf("%d
", Kmp());
55     }
56     return 0;
57 }
原文地址:https://www.cnblogs.com/ykzou/p/4460412.html