题目链接:点击打开链接
给你两个字符串,问你前一个字符串在后一个字符串中出现了几次。
简单修改hdoj2087代码即可ac,就是交换了一下输入顺序,以及此题kmp()函数中j不归零。
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 1e6 + 6;
char s1[MAXN], s2[MAXN];
int nxt[MAXN], len1, len2;
void get_nxt()
{
nxt[1] = 0;
int j = 0;
for(int i = 2; i <= len2; ++i) {
while(j > 0 && s2[j + 1] != s2[i])
j = nxt[j];
if(s2[j + 1] == s2[i]) j++;
nxt[i] = j;
}
}
int kmp()
{
int j = 0, ans = 0;
for(int i = 1; i <= len1; ++i) {
while(j > 0 && s2[j + 1] != s1[i])
j = nxt[j];
if(s2[j + 1] == s1[i]) j++;
if(j == len2) ans++;
}
return ans;
}
int main(int argc, char const *argv[])
{
int t;
scanf("%d", &t);
while(t--) {
scanf("%s", s2 + 1);
scanf("%s", s1 + 1);
memset(nxt, 0, sizeof(nxt));
len1 = strlen(s1 + 1), len2 = strlen(s2 + 1);
get_nxt();
printf("%d\n", kmp());
}
return 0;
}