HDOJ 2087 剪花布條【KMP】

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1001
int next[MAX];
char s[MAX], q[MAX];
void getNext(char s[])
{
	int i, j;
	j = -1;
	next[0] = -1;
	for(i=1; i<strlen(s); i++)
	{
		while(j >= 0 && s[j+1] != s[i])
			j = next[j];
		if(s[j+1] == s[i])
			j++;
		next[i] = j;
	}
}	
int main()
{
	int i, j, ans;
	while(scanf("%s %s", s, q) && s[0] != '#')
	{
		ans = 0;
		getNext(q);
		j = -1;
		for(i=0; i<strlen(s); i++)
		{
			while(j >= 0 && q[j+1] != s[i])
				j = next[j];
			if(q[j+1] == s[i])
				j++;
			if(j == strlen(q)-1)
			{
				ans++;
				j = -1;
			}
		}
		printf("%d\n", ans);
	}
			
		
	system("pause");
	return 0;
}


發佈了164 篇原創文章 · 獲贊 1 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章