CSU 1598: 最长公共前缀(KMP匹配)
【摘要】
题目:
Description
给定两个字符串s和t,现有一个扫描器,从s的最左边开始向右扫描,每次扫描到一个t就把这一段删除,输出能发现t的个数。
Input
第一行包含一个整数T(T<=50),表示数据组数。每组数据第一行包含一个字符串s,第二行一个字符串t,字符串长度不超过1000000。
Ou...
题目:
代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
char s[1000005], t[1000005];
int nextt[1000005];
void getnext(char *p, int m, int *next)
{
int i = 1, j = 0;
next[0] = next[1] = 0;
while (i < m)
{
if (j == 0 || p[i] == p[j])
{
i++;
j++;
if (p[i] != p[j])next[i] = j;
else next[i] = next[j];
}
else j = next[j];
}
}
int main()
{
int n;
cin >> n;
while (n--)
{
scanf("%s%s", s + 1, t + 1);
int ls = strlen(s + 1), lt = strlen(t + 1);
getnext(t, lt, nextt);
int sum = 0;
int i = 1, j = 1;
while (i <= ls)
{
if (j == 0)i++, j++;
else if (s[i] == t[j])
{
i++, j++;
if (j > lt)sum++, i--, j = 0;
}
else j = nextt[j];
}
printf("%d\n", sum);
}
return 0;
}
文章来源: blog.csdn.net,作者:csuzhucong,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/nameofcsdn/article/details/79699826
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)