KMP模板

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cmath>
const int MAXN=1000000+5;
using namespace std;
char s1[MAXN],s2[MAXN];
int nxt[MAXN];
void getnxt(char s[]){
	nxt[0]=-1;
	int len=strlen(s);
	int k=-1,j=0;
	while(j<len){
		/*if(k==-1||s[k]==s[j]){
			k++;j++;
			if(s[k]!=s[j]){
				nxt[j]=k;
			}else nxt[j]=nxt[k];
		}else k=nxt[k];*/
                if(k == -1 || s[k] == s[j]) {
                    nxt[++j] = ++k;
                }else k = nxt[k];
	}
}
void kmp(){
	int i=0,j=0;
	int len1=strlen(s1),len2=strlen(s2);
	while(i<len1){
		if(j==-1||s1[i]==s2[j]){
			i++;j++;
		}else j=nxt[j];
		if(j==len2) {printf("%d\n",i-j+1);j=nxt[j];}
	}
}
int main(){
	freopen("in.txt","r",stdin);
	scanf("%s %s",s1,s2);
	getnxt(s2);
	kmp();
	int lenn=strlen(s2);
	for(int i=1;i<=lenn;i++){
		printf("%d ",nxt[i]);
	}
	fclose(stdin);
	return 0;
}
posted @ 2017-11-30 20:40  Mr_Wolfram  阅读(151)  评论(0编辑  收藏  举报