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('张三', '张四'));