您的位置:首页 > 其它

KMP

2016-04-22 16:27 225 查看
输入

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

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

其中N<=20

输出

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

#include "iostream"
#include "algorithm"
#include "string"
using namespace std;

int main()
{
int test;
cin >> test;
while(test--)
{
string t, s;
cin >> t >> s;
int next[10001];
int i = 0;
int j = -1;
int len1 = t.length();
int len2 = s.length();
next[0] = -1;
while(i < len1)
{
if(j == -1 || t[i] == t[j])
next[++i] = ++j;
else
j = next[j];
}
i = 0;
j = 0;
int ans = 0;
while(i < len2)
{
if(j == -1 || s[i] == t[j])
{
++i;
++j;
}
else
j = next[j];
if(j == len1)
ans++;
}
cout << ans << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: