KMP算法

 

int next[1024] = { -1 };

void MyNext(char *sub)
{
	int len = strlen(sub);
	int k = -1;
	next[0] = -1;
	next[1] = 0;
	int j = 1;
	while (j <= len)
	{
		if (k == -1 || sub[k] == sub[j])
		{
			k++;
			j++;
			next[j] = k;
		}
		else
			k = next[k];
	}

}

int MyKMP(char *src, char *sub)
{
	int src_len = strlen(src);
	int sub_len = strlen(sub);
	int i, j;
	i = j = 0;
	while (i < src_len && j<sub_len)
	{
		if (src[i] == sub[j])
		{
			i++;
			j++;
		}
		else {
			i++;
			j = next[j];
		}
		if (j == -1)
			j = 0;
	}

	if (j > sub_len)
	{
		return i - j;
	}
	return -1;
}

  KMP子串匹配算法精髓在确定next数组上,确定next数组注意以下几点:

  • next[0]=-1;  
  • next[1]=0;
  • 前面两点是固定的。后面的需要通过递归的思想推导出来:

试想next[j]=k,那么next[j+1]应该等于多少,如果string[j]=string[next[j]],那就说明,next[j+1]可以直接递归算出等于 next[j]+1

如果string[j] != string[next[j]],那么递归匹配string[j] != string[next【next【j】】,一直到next[0] +1=0。

posted @ 2019-02-22 17:56  仙7道  阅读(117)  评论(0)    收藏  举报