0
点赞
收藏
分享

微信扫一扫

LIGHTOJ 1255-SUBSTRING FREQUENCY 【KMP】

郝春妮 2023-03-03 阅读 27


题目链接:​​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 条评论