您的位置:首页 > 其它

POJ3461 KMP快速字符串匹配

2016-02-01 15:43 267 查看
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;

const int dmax=1000100;
char s[dmax],p[dmax];
int next[dmax];

void get_next(char *p){
	int k=-1,j=0,n=strlen(p);
	next[0]=-1;
	while (j<n){
		if (k==-1 || p[k]==p[j]){
			k++;
			j++;
			if (p[j]!=p[k])
				next[j]=k;
			else next[j]=next[k];
		}else k=next[k];
	}
}
int kmp(char *s,char *p){
	int i=0,j=0,x=strlen(s),y=strlen(p),ans=0;
	get_next(p);
	while (i<x){
		if (j==y){
			ans++;
			j=next[j];
		}
		if (j==-1 || s[i]==p[j]){
			i++;
			j++;
		}else j=next[j];
	}
	if (j==y)
		ans++;
	return ans;
}

int main(){
	int T;
	scanf("%d",&T);
	getchar();
	while (T--){
		memset(p,0,sizeof(p));
		memset(s,0,sizeof(s));
		memset(next,0,sizeof(next));
		gets(p);
		gets(s);
		printf("%d\n",kmp(s,p));
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: