代码改变世界

字符串匹配BF

2012-04-08 12:46  璋廊  阅读(162)  评论(0编辑  收藏  举报
/*****输入两个字符串,寻找第二个是第一个的字串;此算法是kmp相比古老算法效率更高;
************/
#include<stdio.h>
#include<string.h>
void Getnext(char *t,int *next)
{
	int i,j,k;
	k=strlen(t);
	next[0]=0;
	i=0;j=-1;
	while(i<k)
	{
		if(j==-1||t[i]==t[j])
		{
			i++;j++;
			next[i]=j;
		}
		else j=next[j];
	}
}
int KMP(char *s,char *t,int *next)
{
	int k,h,j,i;
	k=strlen(s);
	h=strlen(t);
	j=0;i=0;
	while(i<k&&j<h)
	{
		if(j==0||s[i]==t[i])
		{
			i++;
			j++;
		}
		else j=next[j];
	}
	if(j==h)
		return i-h+1;
	else return -1;
}

int main()
{
	int pos;
	int next[101];
	char s[1001],t[101];
	scanf("%s%s",s,t);
	Getnext(t,next);
	pos=KMP(s,t,next);
	if(pos==-1)
	{
		printf("很遗憾没有匹配成功!\n");
	}
	else printf("成功啦pos=%d\n",pos);
	return 0;
}