思路:
和普通的匹配问题稍有不同的是本题匹配到的字符串在母串上可以不相连,但也不能相交。
主体思路不难想,考虑记录字符串的所有前缀匹配到的最小位置,记录字符串的所有后缀匹配到的最大位置,只要不相交就可以了,在实现时可以不这么麻烦,直接记录当前缀匹配的最大长度,当前后缀匹配的最大长度,只要合大于等于匹配串的长度就可以了。
注意特判长度为1的字符串不满足题意。
代码是KMP
Code:
#include <iostream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <vector>
#include <string>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
//#include <unordered_map>
#define guo312 std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define ll long long
#define Inf LONG_LONG_MAX
#define inf INT_MAX
#define endl "\n"
#define PI 3.1415926535898
using namespace std;
const int N=2e5+10;
string str1,str2;
int _next[N];
void getnext(){ // next数组
int len=str2.length()-1;
for(int i=2,j=0;i<=len;i++){
while(j&&str2[i]!=str2[j+1]) j=_next[j];
if(str2[i]==str2[j+1]) j++;
_next[i]=j;
}
}
int maxn_len[N];
bool check(){
getnext();
int len1=str1.length()-1,len2=str2.length()-1;
if(len2==1) return 0;
for(int i=1,j=0;i<=len1;i++){
while(j&&str1[i]!=str2[j+1]) j=_next[j];
if(str1[i]==str2[j+1]) j++;
maxn_len[i]=max(maxn_len[i-1],j); // 记录匹配到的最长前缀
if(j==len2) j=_next[j];
}
reverse(str2.begin()+1,str2.end()); // 反转
getnext();
for(int i=len1,j=0,now=0;i>=1;i--){
while(j&&str1[i]!=str2[j+1]) j=_next[j];
if(str1[i]==str2[j+1]) j++;
now=max(now,j); // 匹配到的最长后缀
if(now+maxn_len[i-1]>=len2) return 1;
}
return 0;
}
int main(){
guo312;
cin>>str1; str1="#"+str1; // 从 1 开始 个人习惯
int n,ans=0; cin>>n;
for(int i=1;i<=n;i++){
cin>>str2; str2="#"+str2;
if(check()) ans++;
}
cout<<ans;
return 0;
}