LeeBlog

导航

HDU 2087剪花布条 KMP

KMP算法入门题  哥第一次写KMP惭愧啊,惭愧getnext写得蛋痛,后面的KMP部分更蛋痛。改了N久

#include<stdio.h>
#include<string.h>
#define Max 1005
char str[Max+5] = {0},ch[Max+5] = {0};
int next[Max+5],count = 0,n;
void getnext(  )
{
	int i = 0,j = -1;
	next[0] = -1;
	while( ch[i] )
	{
		if( j == -1 || ch[i] == ch[j] )
			++i,++j,next[i] = j;
		else
			j = next[j];
	}
	n = i;
}
void KMP(  )
{
	int i = 0, j = 0;
	while( str[i] )
	{
		
		if( j == -1 || str[i] == ch[j] )
			++j,++i; 
		while( str[i] && ch[j] && str[i] == ch[j] )
					++i,++j;
		if( j == n )
			++count,j = 0;
		else
			j = next[j];
	}
}
int main( )
{
	while( scanf( "%s",str ),str[0] != '#' )
	{
		scanf( "%s",ch );
		n = count = 0;
		getnext(  );
		KMP(  );
		printf( "%d\n",count );
	}
	return 0;
}

这是final版。。。改了好久啊。。。

posted on 2011-02-01 12:22  LeeBlog  阅读(251)  评论(0编辑  收藏  举报