zoukankan      html  css  js  c++  java
  • Substring Frequency (KMP)

    Substring Frequency

    Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

    Description

    A string is a finite sequence of symbols that are chosen from an alphabet. In this problem you are given two non-empty strings A and B, both contain lower case English alphabets. You have to find the number of times B occurs as a substring of A.

    Input

    Input starts with an integer T (≤ 5), denoting the number of test cases.

    Each case starts with two lines. First line contains A and second line contains B. You can assume than 1 ≤ length(A), length(B) ≤ 106.

    Output

    For each case, print the case number and the number of times B occurs as a substring of A.

    Sample Input

    4

    axbyczd

    abc

    abcabcabcabc

    abc

    aabacbaabbaaz

    aab

    aaaaaa

    aa

    Sample Output

    Case 1: 0

    Case 2: 4

    Case 3: 2

    Case 4: 5

    Hint

    Dataset is huge, use faster I/O methods.

    算法:KMP

     1 #include <iostream>
     2 #include <string>
     3 #include <cstdio>
     4 #include <cstring>
     5 using namespace std;
     6 
     7 const int maxn = 1000001;
     8 char pattern[maxn], target[maxn];
     9 int prefix[maxn];
    10 int lenp, lent;
    11 int cnt, t, ca;
    12 
    13 void GetPrefix()
    14 {
    15     int i = 0, j = -1;
    16     prefix[0] = -1;
    17     while(i < lenp)
    18     {
    19         if(j == -1 || pattern[i] == pattern[j])
    20         {
    21             i++;
    22             j++;
    23             prefix[i] = j;
    24         }
    25         else j = prefix[j];
    26     }
    27 }
    28 
    29 void KMP()
    30 {
    31     GetPrefix();
    32     int i = 0, j = 0;
    33     while(i < lent)
    34     {
    35         if(target[i] == pattern[j] || j == -1)
    36         {
    37             j++;
    38             i++;
    39         }
    40         else j = prefix[j];
    41         if(j == lenp)
    42         {
    43             j = prefix[j];
    44             cnt++;
    45         }
    46     }
    47 }
    48 
    49 int main()
    50 {
    51     scanf("%d", &t);
    52     ca = 1;
    53     while(t--)
    54     {
    55         scanf("%s %s", target, pattern);
    56         lenp = strlen(pattern);
    57         lent = strlen(target);
    58         cnt = 0;
    59         KMP();
    60         printf("Case %d: %d\n", ca++, cnt);
    61     }
    62     return 0;
    63 }
  • 相关阅读:
    H5相关网址
    ASP.NET MVC Razor视图引擎攻略
    深度解析 ASP.NET MVC 5
    .Net MVC 框架基础知识
    java SDK服务端推送 --极光推送(JPush)
    Nexus Repository Manager OSS 3.x 安装配置
    java项目中使用ffmpeg剪辑部分视频
    net 异步与同步
    IDEA把spring-boot项目打包成jar
    开放api接口签名验证
  • 原文地址:https://www.cnblogs.com/cszlg/p/3007235.html
Copyright © 2011-2022 走看看