求字符串编辑距离的递推和递归实现

递推实现:

int CalculateDis_DP(char *str1,char *str2) 
{  
	int i, j;
	int len1=strlen(str1), len2=strlen(str2);  
    
	for (i=0; i<=len2; i++)  
        d[0][i] = i;  
     
	for (i=0; i<=len1; i++)  
        d[i][0] = i;  
    
	for (i=1; i<=len1; i++)  
        for (j=1; j<=len2; j++)  
        { 
			int cost = (str1[i] == str2[j]) ? 0 : 1;    
		
			int deletion = d[i-1][j] + 1;    
			int insertion = d[i][j-1] + 1;    
			int substitution = d[i-1][j-1] + cost;    
		
			d[i][j] = min(deletion,insertion,substitution);  
        }  
	return d[len1][len2];
}
递归实现:

int CalculateDis_Recurse(char str1[], int astart, int aend, char str2[], int bstart, int bend)
{
	if (astart > aend)
	{
		if (bstart < bend)
			return bend-bstart+1;
		else
			return 0;
	}

	if (bstart > bend)
	{
		if (astart < aend)
			return aend-astart+1;
		else
			return 0;
	}

	if (str1[astart] == str2[bstart])
	{
		return CalculateDis_Recurse(str1, astart+1, aend, str2, bstart+1, bend);
	}

	else
	{
		int min1 = CalculateDis_Recurse(str1, astart+1, aend, str2, bstart, bend);
		int min2 = CalculateDis_Recurse(str1, astart, aend, str2, bstart+1, bend);
		int min3 = CalculateDis_Recurse(str1, astart+1, aend, str2, bstart+1, bend);
		return min(min1,min2,min3)+1;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值