LIGHTOJ 1255-SUBSTRING FREQUENCY 【KMP】

来源:互联网 发布:lcd字库生成软件 编辑:程序博客网 时间:2024/05/21 17:21

题目链接:http://www.lightoj.com/volume_showproblem.php?problem=1255

题意:求母串中包含子串的个数,可重叠。

代码:

#include <stdio.h>  #include <iostream>  #include <math.h>  #include <stdlib.h>  #include <ctype.h>  #include <algorithm>  #include <vector>  #include <string.h>  #include <queue>  #include <stack>  #include <set>  #include <map>  #include <sstream>  #include <time.h>  #include <malloc.h>  using namespace std;void get_next(char x[], int m, int Next[]){    int i, j;    j = Next[0] = -1;    i = 0;    while (i < m)    {        while (-1 != j && x[i] != x[j]) j = Next[j];        Next[++i] = ++j;    }}int Next[1001000];long long KMP(char x[], int m, char y[], int n)//x模式串 y主串{    int i, j;    long long ans = 0;    i = j = 0;    get_next(x, m, Next);    while (i < n)    {        while (-1 != j && y[i] != x[j])            j = Next[j];        i++; j++;        if (j >= m)        {            ans++;            j = Next[j];        }    }    return ans;}char a[1000100], b[1000100];int main(){    int t, num;    scanf("%d", &t);    for (int i = 1; i <= t; i++)    {        printf("Case %d: ", i);        scanf("%s", a);        int n = strlen(a);        scanf("%s", b);        int m = strlen(b);        printf("%lld\n", KMP(b, m, a, n));    }}
0 0
原创粉丝点击