刚开始看到这题时认为这题很简单,实际上也确实如此
题目大意为给定两个字符串 s 和 t,求 s 有多少个连续子串,满足 t 是该子串的子序列。
我们可以用预处理 + 补集转化来高效求解。
- 预处理出每个位置 i 开始,最早匹配完 t 的右端点 。
- 总子串数量为 。不合法子串数量:对每个起点 i,不合法子串是 i 到 。 3. 答案 = 总子串数 − 不合法子串数。
时间复杂度 ,可以轻松通过本题。
最后附上code
#include<bits/stdc++.h>
using namespace std;
const int MAXN=100005;
const int MAXM=105;
int nxt[MAXN][MAXM];
int main(){
string s,t;
cin>>s>>t;
int n=s.size(),m=t.size();
s=" "+s; t=" "+t;
for(int i=1;i<=n;i++){
int p=i;
for(int j=1;j<=m;j++){
while(p<=n&&s[p]!=t[j]) p++;
if(p>n) nxt[i][j]=-1;
else nxt[i][j]=p,p++;
}
}
long long tot=1LL*n*(n+1)/2;
long long no=0;
for(int i=1;i<=n;i++){
if(nxt[i][m]==-1) no+=n-i+1;
else no+=nxt[i][m]-i;
}
cout<<tot-no<<endl;
return 0;
}