美团笔试题之一:求编辑距离

本文介绍了一种计算两个字符串之间编辑距离的算法实现,通过递归方式处理字符串转换过程中的添加、删除和替换操作,提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:给定一个源字符串src=“string”,然后给定一个目标字符串dst=“strim”,可以通过添加、删除和替换字符使得源字符串转化为目标字符串,比如给的例子中可以将“n"替换成“m”,然后删除“g”,则源字符串转换为目标字符串,源字符串变换为目标字符串时经过的最小动作(添加、删除和替换)数为源字符串到目标字符串的编辑距离,编写程序求出给定源字符串和目标字符串的编辑距离,如例子中的编辑距离为2.

解题的主要思路为:(递归)

分为两种情况:(rsc,dst)

(一)当判断的两个字符相等时(*rsc==*dst),编辑距离为前面的编辑距离加上后面的编辑距离help(rsc++,dst++)的距离;

(二)不相等时分为三种情况:

1,在该位置进行替换元素,编辑距离为1+help(rsc++,dst++);

2,当在该位置添加元素时编辑距离为1+help(rsc,dst++);

3,当在该位置删除一个元素时编辑距离为1+help(rsc++,dst)

具体代码如下:

#include "stdafx.h"
#include<iostream>
using namespace std;
int compute_lenth(char *src)
{
	int i = 0;
	while (src[i] != '\0')
	{
		i++;
	}
	return i;
}
int help(char*src, char *dst)
{
	if (*src == '\0')
		return compute_lenth(dst);
	if (*dst == '\0')
		return compute_lenth(src);
	if (*src == *dst)
		return help(src + 1, dst + 1);
	else
		{
			int temp = 100000;
			int result = 1000001;
			result = 1 + help(src + 1, dst + 1); //tihuan
			if (result < temp)
				temp = result;
			//tianjia
			result = 1 + help(src, dst + 1);
			if (result < temp)
				temp = result;
			result = 1 + help(src + 1, dst);//shanchu
			if (result < temp)
				temp = result;
			return temp;
		}
}
int edit_distance(char *src, char *dst) {
	return help(src, dst);
}

int _tmain(int argc, _TCHAR* argv[])
{
	int result = edit_distance("string", "strim");
	cout << result << endl;
	return 0;
}
注:代码为自己编写,可能会存在问题,如有问题请在评论中指出或邮件告知,谢谢。本代码通过VS2013下编写,并通过了笔试时的所有用例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值