#1015 : KMP算法

输入

第一行一个整数N,表示测试数据组数。

接下来的N*2行,每两行表示一个测试数据。在每一个测试数据中,第一行为模式串,由不超过10^4个大写字母组成,第二行为原串,由不超过10^6个大写字母组成。

其中N<=20

输出

对于每一个测试数据,按照它们在输入中出现的顺序输出一行Ans,表示模式串在原串中出现的次数。

样例输入

5
HA
HAHAHA
WQN
WQN
ADA
ADADADA
BABABB
BABABABABABABABABB
DAD
ADDAADAADDAAADAAD

样例输出

3
1
3
1
0

//#include <cstdio>
#include <iostream>
//#include <algorithm>
//#include <cstring>
#include <string>
#include <vector>
using namespace std;

int KMP(string t, string p){
int n = p.size(); //一个 int 类型n+1个元素,且值均为0的vecotr容器
vector<int> next(n + 1, 0);
for (int i = 1; i < n; i++)
{
int j = i;
while (j>0)
{
j = next[j];
if (p[j] == p[i])
{
next[i + 1] = j + 1;
break;
}
}

}

int ans = 0;
int m = t.size();
for (int i = 0, j = 0; i < m; i++)
{
if (j<n && p[j] == t[i]) j++;
else{
while (j>0)
{
j = next[j];
if (p[j] == t[i])
{
j++;
break;
}
}
}
if (j == n) ans++;
}

return ans;
}

int main(){
string t, p;
int n;
cin >> n;
while (n--)
{
cin >> p>>t;
int ans=KMP(t, p);
cout << ans << endl;
}
return 0;
}

posted @ 2017-08-07 09:36  code666  阅读(120)  评论(0编辑  收藏  举报