poj 3461 (模式串T在主串S中出现的次数)

求模式串在主串中出现的次数
Sample Input

3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN
Sample Output

1
3
0

 #include <iostream>
#include <cstring>
using namespace std; const int N = ;
int next[N];
char S[N], T[N];
int slen, tlen; void getNext()
{
int j, k;
j = ; k = -; next[] = -;
while(j < tlen)
if(k == - || T[j] == T[k])
next[++j] = ++k;
else
k = next[k]; } /*
返回模式串在主串S中出现的次数
*/
int KMP_Count()
{
int ans = ;
int i, j = ; if(slen == && tlen == )
{
if(S[] == T[])
return ;
else
return ;
}
getNext();
for(i = ; i < slen; i++)
{
while(j > && S[i] != T[j])
j = next[j];
if(S[i] == T[j])
j++;
if(j == tlen)
{
ans++;
j = next[j];
}
}
return ans;
}
int main()
{ int TT;
int i, cc;
cin>>TT;
while(TT--)
{
cin>>T>>S;
slen = strlen(S);
tlen = strlen(T); cout<<KMP_Count()<<endl;
}
return ;
}
上一篇:二分法-C++


下一篇:EM and GMM(Code)