KMP

void Make_Next (char *str)  {
	int len = strlen (str + 1);
	for (int i = 2, j = 0; i <= len; i++) {
		while (j != 0 && str[j + 1] != str[i]) j = next[j];
		if (str[j + 1] == str[i]) {
			j++;
		}
		next[i] = j;
	}
}

int KMP (char *sa, char *sb) {
	int lena = strlen (sa + 1), lenb = strlen (sb + 1);
	for (int i = 1, j = 0; i <= lena && j <= lenb; i++) {
		while (j != 0 && sb[j + 1] != sa[i]) j = next[j];
		if (sb[j + 1] == sa[i]) {
			j++;
		}
		if (j == lenb) {
			return i - j + 2;
		}
	}
	return -1;
}
posted @ 2020-11-14 11:52  C2022lihan  阅读(18)  评论(0编辑  收藏  举报