题意:求模式串在待匹配串的出现次数。
解法:1、使用朴素解法,遍历模式串一次,然后待匹配串往后移动一个字符。时间复杂度O(nm)。
2、使用KMP算法,求出模式串的Next数组,然后对待匹配串匹配,令i是待匹配串位置指针,j是模式串位置指针。当j等于模式串的长度,即完成一次匹配。令j=next[j]回溯即可。
AC代码:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int nextarray[10005];
void getnext(string &a)
{
memset(nextarray, 0, sizeof(nextarray));
int k = 0, j = -1;
nextarray[0] = -1;
while (k != a.size())
{
if (j == -1 || a[j] == a[k])
nextarray[++k] = ++j;
else
j = nextarray[j];
}
}
int count(string &a, string &b)
{
int i = 0, j = 0, ans = 0;
while (i < a.size())
{
if (j == -1 || a[i] == b[j])
++i, ++j;
else
j = nextarray[j];
if (j == b.size())
++ans, j = nextarray[j];
}
return ans;
}
int main()
{
int n;
cin >> n;
string a, b;
while (n--)
{
cin >> a >> b;
getnext(a);
cout << count(b, a) << endl;
}
return 0;
}