编写算法,统计子串t在主串s中出现的次数。
输入格式:
首先输入一个整数T,表示测试数据的组数,然后是T组测试数据。每组测试数据在第一行中输入主串s,在第二行中输入子串t,s和t中不包含空格。
输出格式:
对于每组测试,若子串t在主串s中出现,则输出t在s中的子串位置和出现总次数,否则输出0 0
。
输入样例:
2
abbbbcdebb
bb
abcde
bb
输出样例:
2 4
0 0
/*
#include<stdio.h>
//输入测试数据
char* get(char*s)
{
char x;
scanf("%c",&x);
while(x!='\0')
*s++=x;
return s;
}
//输出t在s中的子串位置和出现总次数
void count(char *s,char* t)
{
int i=0,j=0;
}
int main()
{
char *s,*t;
s=NULL;
t=NULL;
int T;
scanf("%d",&T); //测试数据的组数
for(;T>=0;T--) //T组测试数据
{
get(s);
get(t);
count(s,t);
}
return0;
}
*/
#include <stdio.h>
#include <string.h>
int nexts[100005];
void getNext(char *str) {
int m = strlen(str);
int j = -1, i = 0;
nexts[0] = -1;
while (i < m - 1) {
if (j == -1 || str[i] == str[j]) {
i++;
j++;
nexts[i] = j;
} else {
j = nexts[j];
}
}
}
int main() {
int n;
char a[100005], b[100005];
scanf("%d", &n);
while (n--) {
int f = -1;
int time = 0;
scanf("%s%s", a, b);
getNext(b);
int i = 0, j = 0;
int lenb = strlen(b);
int lena = strlen(a);
while (i < lena) {
if (j == -1 || a[i] == b[j]) {
i++;
j++;
} else {
j = nexts[j];
}
if (j == lenb) {
time++;
if (f == -1)
f = i - j;
j = 0;
if (lenb > 1)
i--;
}
}
printf("%d %d\n", f + 1, time);
}
return 0;
}