KMP

// Name      : KMP
// Parameter : tex[]:主串 pat[]:模式串
// Return    : 匹配数
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
const int maxn=1005;
int KMP(char tex[],char pat[]){
	int overlap[maxn];
	memset(overlap,-1,sizeof(overlap));
	int l=strlen(tex),m=strlen(pat);
	overlap[1]=0;
	for(int i=2;i<=m;i++){
		int j=overlap[i-1];
		while(j!=-1 && pat[i-1]!=pat[j])
			j=overlap[j];
		overlap[i]=j+1;
	}
	int ans=0;
	for(int i=0,j=0;;){
		if(j==m){ ans++; j=overlap[m]; }
		if(i==l) break;
		if(j==-1 || tex[i]==pat[j]) { i++;j++; }
		else j=overlap[j];
	}
	return ans;
}
int main() {
	char t[maxn],p[maxn];
	while(scanf("%s%s",t,p)){
		printf("%d\n",KMP(t,p));
	}
	return 0;
}

// Name      : KMP
// Parameter : tex[]:主串 pat[]:模式串
// Return    : 第一处匹配位置
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
const int maxn=1005;
int KMP(char tex[],char pat[]){
	int overlap[maxn];
	memset(overlap,-1,sizeof(overlap));
	int l=strlen(tex),m=strlen(pat);
	overlap[1]=0;
	for(int i=2;i<=m;i++){
		int j=overlap[i-1];
		while(j!=-1 && pat[i-1]!=pat[j])
			j=overlap[j];
		overlap[i]=j+1;
	}
	for(int i=0,j=0;;){
		if(j==m){ return i-j+1; }
		if(i==l) break;
		if(j==-1 || tex[i]==pat[j]) { i++;j++; }
		else j=overlap[j];
	}
	return -1;
}
int main() {
	char t[maxn],p[maxn];
	while(scanf("%s%s",t,p)){
		printf("%d\n",KMP(t,p));
	}
	return 0;
}

  

posted on 2013-08-13 10:13  Amyc  阅读(156)  评论(0编辑  收藏  举报