KMP

来源:互联网 发布:关了蜂窝数据还跑流量 编辑:程序博客网 时间:2024/06/05 21:59

输入
第一行一个整数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;}
0 0
原创粉丝点击