zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    iOS去除导航栏和tabbar的横线
    各种坑
    iOS系统消息
    文件的读写
    MAC机中安装ruby环境--转载
    一句话处理服务器头像的尺寸
    开一个线程来处理 耗时的操作
    angular2中一种换肤实现方案
    一句话说明==和equals的区别
    下拉框样式在不同浏览器的简单兼容
  • 原文地址:https://www.cnblogs.com/ykzou/p/4460412.html
Copyright © 2011-2022 走看看