现在的位置: 首页 > 综合 > 正文

字符串匹配算法

2018年02月11日 ⁄ 综合 ⁄ 共 1140字 ⁄ 字号 评论关闭

字符串匹配算法有很多种,最为常用的有KMP算法、普通算法。

1、普通算法:此算法是效率最低的算法,时间复杂度为O(NM)。

程序如下:

bool str_match(const char * str1, const char * str2)//O(P*T)
{
	assert(str1 != NULL && str2 != NULL);
	int k = 0;
	for (unsigned int i = 0; i < strlen(str1); i ++)
	{
		k = i;
		for (unsigned int j = 0; j < strlen(str2); j ++)
		{
			if (*(str1 + k++) == *(str2 + j))
			{
				if (j == strlen(str2)-1)
					return true;
			}
			else 
				break;
		}
	}
	return false;
}

2、KMP算法,KMP算法可以说是在普通算法上的改进的算法,在普通算法中,在字符串P中每一次只移动一个字符,而在KMP算法中,根据后缀表达式相同的方法,可以跳过几个字符,在算法执行开始需要找出每次移动的字符数。

程序如下:

////---------------------------------------------------KMP-------------//
void findNext(const char * strP, int * next)
{
	assert(strP != NULL && next != NULL);
	int lenP = strlen(strP);
	*next = -1;
	int i = 0;
	int j = -1;
	while (i < lenP)
	{
		while (j == -1 || j < lenP && *(strP+i) == *(strP + j) )
		{
			j++;
			i++;
			if(*(strP+i) != *(strP + j))
				next[i] = j;
			else
				next[i] = next[j];
		}
		j = next[j];
	}
}
int KMP(const char * strP, const char *strT)
{
	assert(strP != NULL && strT != NULL);
	int lenP = strlen(strP);
	int * next = new int[lenP];
	findNext(strP,next);
	int i = 0;
	int j = 0;
	int lenT = strlen(strT);
	while (i <= strT-strP)
	{
		while (j == -1 || j < lenP && *(strP+j) == *(strT + i))
		{
			i++;
			j++;
		}
		if (j == lenP)
		{
			return i - lenP;
		}
		j = *(next+j);
	}
	delete [] next;
	return -1;
}
//--------------------------------------end of KMP-------------------------------------//

抱歉!评论已关闭.