C/C++: 数据结构之KMP算法

/**
* 
*  Althor:Hacker Hao
*  Create:2023.10.11
* 
*/
#include 
using namespace std;

#define maxn 200
int kmp[maxn];
char t[maxn], p[maxn];
int main()
{
	cout << "请输入文本串:" << endl;
	cin >> t;
	cout << "请输入模式串:" << endl;
	cin	>> p;

	int lent = strlen(t);
	int lenp = strlen(p);
	
	//下文中,index表示“指针”,length表示前后缀的最长长度
	for (int index = 0, length = 0; index < lenp; index++)
	{
		while (length && p[length] != p[index])
			length = kmp[length];
		if (p[length] == p[index])
			length++;
		kmp[index] = length;
	}

	for (int index = 0, length = 0; index < lent; index++)
	{
		while (length && p[length] != t[index])
		{
			length = kmp[length];
		}
		if (p[length] == t[index])
			length++;
		if (length == lenp)
		{
			cout << index - lenp + 2;
			break;
		}
	}

	return 0;
}

你可能感兴趣的:(算法,数据结构,c++,c语言)