数据结构算法(2)--字符串匹配

数据结构算法(2)--字符串匹配

总结并记录学习数据结构过程中遇到的问题及算法.


一些常见算法:

Note:

  • 字符串匹配--KMP算法.

求next数组

void getNext(char *next, char *p)
{
	int len = strlen(p);
	int k = -1, j = 0;
	next[0] = -1;
	while (j < len-1)
	{
		if (k == -1 || p[k] == p[j])  //p[k]表示前缀,p[j]表示后缀
		{
			++j;
			++k;
			next[j] = k;
		}
		else
		{
			k = next[k];
		}
	}
}

匹配算法

int KMPsearch(char *T, char *P, char *next)
{
	int n = strlen(T);
	int m = strlen(P);
	int i = 0, j = 0;
	while (i < n&&j<m)
	{

		if (j==-1||T[i] == P[j])
		{
			++i;
			++j;
		}
		else
		{
			j = next[j];
		}
	}
	if (j == m)
		return i - j;
	else
		return -1;
}

详细分析见博客 https://blog.csdn.net/v_july_v/article/details/7041827

posted @ 2019-03-05 18:03  会煮面  阅读(175)  评论(0编辑  收藏  举报