KMP算法:version02(改进版)

#include<iostream>
#include<string>

using namespace std;

int* buildNext(string P)
{
	//构造模式串P的next表
	size_t m = P.length(), j = 0;//主串指针
	int* N = new int[m];//next表
	int t = N[0] = -1;//模式串指针
	while (j<m-1)
	{
		if (0 > t || P[j] == P[t])
		{
			//匹配
			j++;
			t++;
			N[j] = (P[j]!=P[t]?t:N[t]);
		}
		else
		{
			//失配
			t = N[t];
		}
	}
	return N;
}

//如果匹配成功那么返回值是模式串在文本串中的起始位置,反之
int match(string P, string T)
{
	//KMP算法
	int* next = buildNext(P);//构造next表
	int n = (int)T.length(), i = 0;//文本串指针
	int m = (int)P.length(), j = 0;//模式串指针
	while (j < m && i < n)
	{
		//自左向右逐个比对字符
		if (0 > j || T[i] == P[j])//若匹配,或者P已经移出最左侧(两个判断的次序不可交换)
		{
			i++;
			j++;//则转到下一字符
		}
		else
		{
			//否则
			j = next[j];//模式串右移,文本串不用回退
		}
	}
	delete[]next;//释放next表
	return i - j;
}

int main()
{
	string pattern = "123456789";
	string text = "1234567890abcdefghijklmnopqrstuvwxyz";
	cout << match(pattern, text);
	getchar();
	return 0;
}
发布了69 篇原创文章 · 获赞 33 · 访问量 1196

猜你喜欢

转载自blog.csdn.net/dosdiosas_/article/details/105661372