Description
在实验室里,大家通常都可能会因为一个问题发生分歧,比如找一堆数字中的第k大,zser就会想着划分树!!!而其他人就会用些很菜的做法——排序。因为zser天天都和人有分歧,所以他有着一个txt,上面记录了每天和他最有分歧并且还敢嘲笑他的人的名字str1。同时还有着另一个字符串str2用一种隐蔽的方式记录着那个嘲讽他的程度(不愧是学了网络攻防,隐私保护就是好)。
计算嘲讽程度的方法就是:求这个名字str1在str2中出现了几次。
Input
输入一个T,表示有T天。
每组数据有两个字符串str1,str2。
str1代表名字。
str2代表记录嘲讽程度的字符串。字符串长度小于1e6。
Output
每天被嘲讽的程度,即str1在str2中出现的次数。
Sample Input Copy
2
ALA
ALALA
DD
DDD
Sample Output Copy
2
2
#include<bits/stdc++.h>
using namespace std;
#define ios ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);
int i,j;
string str1;
string str2;
int nex[100100];
int t;
int ans;
void init()
{
i=1,j=0;
while(i<str1.size())
{
if(str1[i]==str1[j]) nex[i]=j+1,i++,j++;
else if(j==0) i++;
else j = nex[j-1];
}
}
int main()
{
cin>>t;
while(t--)
{
ans=0;
memset(nex,0,sizeof(nex));
cin>>str1;
cin>>str2;
if(str1.size()==1)
{
i=0;
while(i<str2.size())
{
if(str2[i]==str1[0])
ans++;
i++;
}
cout<<ans<<endl;
continue;
}
init();
j=0,i=0;
while(i<str2.size())
{
if(j==str1.size()-1&&str2[i]==str1[j])
{
j=nex[j-1];
ans++;
}
else if(str2[i]==str1[j]) i++,j++;
else if(j==0) i++;
else j = nex[j-1];
}
cout<<ans<<endl;
}
return 0;
}