備戰NOIP——模板複習21

這裏只有模板,並不作講解,僅爲路過的各位做一個參考以及用做自己複習的資料,轉載註明出處。

KMP字符串匹配

/*Copyright: Copyright (c) 2018
*Created on 2018-11-06
*Author: 十甫
*Version 1.0 
*Title: KMP
*Time: inf mins
*/
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int size = 1000005;

char a[size], b[size];
int next[size];

int main() {
	memset(next, 0, sizeof(next));
	scanf("%s%s", a + 1, b + 1);
	int n = strlen(b + 1), m = strlen(a + 1);
	next[1] = 0;
	for(int i = 2, j = 0;i <= n;i++) {
		while(j && b[i] != b[j + 1]) {
			j = next[j];
		}
		if(b[i] == b[j + 1]) {
			j++;
		}
		next[i] = j;
	}
	for(int i = 1, j = 0;i <= m;i++) {
		while(j && a[i] != b[j + 1]) {
			j = next[j];
		}
		if(a[i] == b[j + 1]) {
			j++;
		}
		if(j == n) {
			printf("%d\n", i - n + 1);
			j = next[j];
		}
	}
	for(int i = 1;i <= n;i++) {
		printf("%d ", next[i]);
	}
	printf("\n");
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章