E. Martian Strings (kmp)

原题链接

思路:

和普通的匹配问题稍有不同的是本题匹配到的字符串在母串上可以不相连,但也不能相交

主体思路不难想,考虑记录字符串的所有前缀匹配到的最小位置,记录字符串的所有后缀匹配到的最大位置,只要不相交就可以了,在实现时可以不这么麻烦,直接记录当前缀匹配的最大长度,当前后缀匹配的最大长度,只要合大于等于匹配串的长度就可以了。

注意特判长度为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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

要用bug来打败bug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值