字符串匹配算法

字符串匹配算法有很多种,最为常用的有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-------------------------------------//




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值