HDU 1686 Oulipo
- 题意:问模式串在文本串中出现过几次。
- 思路:KMP模板,只需要在得到一个完整的模式串之后,将这种情况当作匹配失败回到 j = next[ j ] 即可
AC CODE
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxN = 1000000 + 7;
int Next[10007];
void GetNext(char *t, int len)
{
int i = 0, j = -1;
Next[0] = -1;
while(i < len)
{
if(j == -1 || t[i] == t[j])
{
++i; ++j;
if(t[i] != t[j])
Next[i] = j;
else
Next[i] = Next[j];
}
else
j = Next[j];
}
}
int KMP(char *s, int s_len, char *t, int t_len)
{
int i = 0, j = 0;
GetNext(t, t_len);
int ans = 0;
while(i < s_len && j < t_len)
{
if(j == -1 || s[i] == t[j]) { ++i; ++ j; }
else j = Next[j];
if(j == t_len)
{
ans++;
j = Next[j];
}
}
return ans;
}
char s[1000007], t[10007];
int main()
{
int TAT; scanf("%d", &TAT);
while(TAT -- )
{
scanf("%s%s", t, s);
printf("%d\n", KMP(s, strlen(s), t, strlen(t)));
}
return 0;
}