百度-20120926-字符串编辑距离

题目:找出字符串的编辑距离,即统计一个字符串s1最少经过多少步操作变成字符串s2?(操作有三种:添加一个字符,删除一个字符,修改一个字符)。

备注:1)一直都推荐阅读最精彩的参考资料,关于Levenshtein distance也即edit distance,请参考wiki:http://en.wikipedia.org/wiki/Levenshtein_distance,wiki给出了非常详细的解答,相信读过之后会让你有收获。2)这题出现了很多大公司的笔试/面试题中,比如google,百度 and so on.

// 这是递归的解法,空间复杂度相当高,不实用
// calculate the edit distance between source and target recursively
int editDistanceRecursive(string source, string target){
	int len_source = source.length();
	int len_target = target.length();
	
	// test for degenerate cases of empty string of source or target string
	if(len_source == 0)
		return len_target;
	if(len_target == 0)
		return len_source;
	
	int cost = 0;
	// check the last character of source and target is equal or not
	if(source[len_source-1] != target[len_target-1])
		cost = 1;
	
	return minimum(editDistanceRecursive(source.substr(0, len_source-1), target)+1, editDistanceRecursive(source, target.substr(0, len_target-1))+1, editDistanceRecursive(source.substr(0, len_source-1), target.substr(0, len_target-1))+cost);	
}

// 面试中应该倾向采用非递归的解法
int editDistanceIteratively(string source, string target){
	int len_source = source.length();
	int len_target = target.length();
	
	// test for degenerate cases of empty string of source or target string
	if(len_source == 0)
		return len_target;
	if(len_target == 0)
		return len_source;
	
	// do initilization
	int** dMatrix = new int*[len_source+1];
	for(int i = 0; i <= len_source; i++){
		dMatrix[i] = new int[len_target+1];
		memset(dMatrix[i], 0, sizeof(int)*(len_target+1));
	}
	
	for(int i = 1; i <= len_source; i++)
		dMatrix[i][0] = i;
	
	for(int i = 1; i <= len_target; i++)
		dMatrix[0][i] = i;
	
	
	for(int j = 1; j <= len_target; j++)
		for(int i = 1; i <= len_source; i++){
			if(source[i-1] == target[j-1]){
				dMatrix[i][j] = dMatrix[i-1][j-1];
			}else{
				dMatrix[i][j] = minimum(dMatrix[i-1][j]+1, dMatrix[i][j-1]+1, dMatrix[i-1][j-1]+1);
			}
		}
	
	return dMatrix[len_source][len_target];
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值