HDU-2087 剪花布条(kmp)

题目大意很好理解,我就不啰嗦了,直接贴代码。

#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1010;
int next[N];
char tar[N],pat[N];
void getNext() {
	int j = 0,k = -1;
	int lenP = strlen(pat);
	next[0] = -1;
	while(j < lenP) {
		if(k == -1 || pat[j] == pat[k]) {
			j++;
			k++;
			next[j] = k;
		}else {
			k = next[k];
		}
	}
}
int kmp(int k) {
	int posP = 0,posT = k;
	int lenT = strlen(tar);
	int lenP = strlen(pat);
	while(posP < lenP && posT < lenT) {
		if(posP == -1 || tar[posT] == pat[posP]) {
			posP++;
			posT++;
		}else {
			posP = next[posP];
		}
	}
	if(posP < lenP) {
		return -1;
	}else {
		return posT - lenP;
	}
}
int main() {
	while(scanf("%s",tar) != EOF && tar[0] != '#') {
		scanf("%s",pat);
		getNext();
		int ans = 0,pos = -1;
		int lenP = strlen(pat);
		while(1) {
			int pos = kmp(pos);
			if(pos != -1) {
				pos += lenP;
				ans++;
			}else {
				break;
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}


你可能感兴趣的:(HDU,剪花布条,2087)