字符串算法模板合集

1、KMP

KMP模板

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#define ll long long
#define INF 2147483647
#define mem(i,j) memset(i,j,sizeof(i))
#define F(i,j,n) for(register int i=j;i<=n;i++)
using namespace std;
char s1[1000010],s2[1000010];
int Next[1000010],l1,l2;
inline int read(){
	int datta=0;char chchc=getchar();bool okoko=0;
	while(chchc<'0'||chchc>'9'){if(chchc=='-')okoko=1;chchc=getchar();}
	while(chchc>='0'&&chchc<='9'){datta=datta*10+chchc-'0';chchc=getchar();}
	if(okoko==1)return -datta;return datta;
}
inline void get_Next(){
	int j=0;
	F(i,1,l2){
		while(j&&s2[j+1]!=s2[i+1])
			j=Next[j];
		if(s2[j+1]==s2[i+1])
			j++;
		Next[i+1]=j;
	}
}
inline void kmp(){
	int j=0;
	F(i,1,l1){
		while(j&&s2[j+1]!=s1[i])
			j=Next[j];
		if(s2[j+1]==s1[i])
			j++;
		if(j==l2){
			printf("%d\n",i-j+1);
			j=Next[j];
		}
	}
}
int main(){
	scanf("%s%s",s1+1,s2+1);
	l1=strlen(s1+1);l2=strlen(s2+1);
	get_Next();
	kmp();
	F(i,1,l2-1)
		printf("%d ",Next[i]);
	printf("%d\n",Next[l2]);
	return 0;
}
posted @ 2019-01-05 00:00  hzf29721  阅读(201)  评论(0编辑  收藏  举报