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\n", Kmp());
55     }
56     return 0;
57 }

 

转载于:https://www.cnblogs.com/ykzou/p/4460412.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值