链接
题解
大写字母必须对应相等
对于小写字母,我先求出每个小写字母和他前面一个相同字母的位置之差,我称之为 d d d值
我把一个串种某种字母第一次出现的位置的字符称为“首字母”
然后匹配规则就变成了:如果是大写字母则必须相同,如果是小写字母则要分两种情况,如果两个串对应位置都是“首字母”,则认为相同(无需关心是哪种首字母),如果两个位置都不是“首字母”则必须 d d d值相同。其它情况都视为失配。
这里仍然使用 k m p kmp kmp来做匹配
具体不太好描述,请看代码
代码
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define iinf 0x3f3f3f3f
#define linf (1ll<<60)
#define eps 1e-8
#define maxn 1000010
#define maxe 1000010
#define cl(x) memset(x,0,sizeof(x))
#define rep(i,a,b) for(i=a;i<=b;i++)
#define drep(i,a,b) for(i=a;i>=b;i--)
#define em(x) emplace(x)
#define emb(x) emplace_back(x)
#define emf(x) emplace_front(x)
#define fi first
#define se second
#define de(x) cerr<<#x<<" = "<<x<<endl
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll read(ll x=0)
{
ll c, f(1);
for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
for(;isdigit(c);c=getchar())x=x*10+c-0x30;
return f*x;
}
struct KMP
{
int n, next[maxn], t[maxn];
bool cmp(int a, int b, int p){return a==b or a>p and b>p;};
void build(int *r, int len)
{
int i, j=0;
n=len;
for(i=1;i<=len;i++)t[i]=r[i]; t[len+1]=0;
for(i=2;i<=len;i++)
{
for(;j and !cmp(t[j+1],t[i],j);j=next[j]);
next[i] = cmp(t[j+1],t[i],j)?++j:0;
}
}
int move(int pos, int x)
{
for(;pos and !cmp(t[pos+1],x,pos);pos=next[pos]);
return cmp(t[pos+1],x,0) ? pos+1 : 0;
}
}kmp;
ll last[maxn], pre[maxn];
int S[maxn], T[maxn];
char s[maxn], t[maxn];
int main()
{
ll Q=read();
while(Q--)
{
ll i, j, n, m;
scanf("%s%s",s+1,t+1);
n=strlen(s+1);
m=strlen(t+1);
rep(i,0,300)last[i]=-1;
rep(i,1,n)
{
pre[i]=last[s[i]];
last[s[i]]=i;
if(islower(s[i]))S[i] = i-pre[i];
else S[i]=-s[i];
}
rep(i,0,300)last[i]=-1;
rep(i,1,m)
{
pre[i]=last[t[i]];
last[t[i]]=i;
if(islower(t[i]))T[i] = i-pre[i];
else T[i]=-t[i];
}
kmp.build(T,m);
ll ans=0, p=0;
rep(i,1,n)
{
p = kmp.move(p,S[i]);
if(p==m)ans++, p=kmp.next[p];
}
printf("%lld\n",ans);
}
return 0;
}