JavaScript 实现字符串匹配度算法

function levenshtein(str1, str2) {
	// 计算两个字符串长度
	const len1 = str1.length;
	const len2 = str2.length;
	// 创建装载数组
	const dif = [];
	for (let i = 0; i < len1 + 1; i++) {
		dif.push(new Array(len2 + 1));
	}
	// 赋初始值
	for (let i = 0; i <= len1; i++) {
		dif[i][0] = i;
	}
	for (let i = 0; i <= len2; i++) {
		dif[0][i] = i;
	}
	// 计算两个字符串是否一样
	const ch1 = str1.split('');
	const ch2 = str2.split('');
	let temp;
	for (let i = 1; i <= len1; i++) {
		for (let j = 1; j <= len2; j++){
			if(ch1[i - 1] == ch2[j - 1]) {
				temp = 0;
			} else {
				temp = 1;
			}
			// 取最小值
			const temp1 = dif[i - 1][j - 1] + temp;
			const temp2 = dif[i][j - 1] + 1;
			const temp3 = dif[i - 1][j] + 1;

			dif[i][j] = Math.min(temp1, temp2, temp3);
		}
	}
	// 计算相似度
	const similarity = 1 - dif[len1][len2] / Math.max(str1.length, str2.length);
	return similarity;
}
console.log(levenshtein('张三', '张四')); // 0.5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值