算法导论之KMP

#include 
#include 

using namespace std;

void makeNext(const string pattern, int *next) {
	int k, q;
	int m = pattern.length();
	next[0] = 0;
	for (k = 0, q = 1; q < m; ++q) {
		while (k > 0 && pattern[q] != pattern[k]) k = next[k - 1];
		if (pattern[q] == pattern[k]) k++;

		next[q] = k;
	}
}
//如果需要查出所有的包含pattern的位置,则使用void的函数,
//如果只要一个可以采用int返回index
void KMP(const string str, const string pattern) {
	int lenPattern = pattern.length();
	int lenStr = str.length();
	int * next = new int[lenPattern]();

	makeNext(pattern, next);
	cout << "最长前后缀相同表:" << endl;
	for (int i = 0; i < lenPattern; i++) cout << next[i] << " ";
	cout << endl;


	for (int i = 0, q = 0; i < lenStr; i++) {
		while (q > 0 && pattern[q] != str[i]) q = next[q - 1];
		if (pattern[q] == str[i]) q++;
		if (q == lenPattern) {
			cout << "找到一个匹配的字符串,其偏移量为:" << i - q + 1 << endl;
			q = next[q - 1];
		}
	}

	if (next != nullptr) {
		delete[] next;
		next = nullptr;
	}

}
int main() {
	string str = "ababxbabaabcdabdbcadfdsss";
	string pattern = "abcdabd";
	KMP(str, pattern);
	return 0;
}



你可能感兴趣的:(算法导论之KMP)