AcWing 831. KMP字符串

阅读 59

2022-01-24

题目连接

https://www.acwing.com/problem/content/description/833/

思路

kmp和暴力匹配的差别就在于我们求了子串的boarder,由于这个boarder有一个对称性,也就是前缀等于后缀,所以我们匹配失败的时候其实不用回到字串的起始地点,让它回到前缀的地方就好了,因为之前的位置都是匹配成功的。

代码

#include<bits/stdc++.h>
using namespace std;
//----------------自定义部分----------------
#define ll long long
#define mod 1000000009
#define endl "\n"
#define PII pair<int,int>

int dx[4]={0,-1,0,1},dy[4]={-1,0,1,0};

ll ksm(ll a,ll b) {
	ll ans = 1;
	for(;b;b>>=1LL) {
		if(b & 1) ans = ans * a % mod;
		a = a * a % mod;
	}
	return ans;
}

ll lowbit(ll x){return -x & x;}

const int N = 2e6+10;
//----------------自定义部分----------------
int n,m,q,a[N],nextt[N];
string s,p;

void get_next(){//求字串的next数组
	int i = 0,j = -1;
	nextt[0] = -1;
	while(i < n){
		if(j == -1 || p[i] == p[j]) nextt[++i] = ++j;
		else j = nextt[j];
	}
}

void kmp(){
	get_next();
	int i = 0,j = 0;
	while(i < m){
		if(j == -1 || p[j] == s[i]) ++i,++j;
		else j = nextt[j];
		if(j == n) cout<<i-n<<" ",j=nextt[j];//匹配成功
	}
}

int main()
{
	std::ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	std::cout.tie(nullptr);
	cin>>n>>p>>m>>s;
	kmp();
	
	
	return 0;
}

精彩评论(0)

0 0 举报