const levenshteinDistance = (str1: string, str2: string) => {
const len1 = str1.length;
const len2 = str2.length;
const matrix: Array<number[]> = [];
// 初始化第一行
for (let i = 0; i <= len1; i++) {
matrix[i] = [i];
}
// 初始化第一列
for (let j = 0; j <= len2; j++) {
matrix[0][j] = j;
}
// 填充矩阵
for (let i = 1; i <= len1; i++) {
for (let j = 1; j <= len2; j++) {
const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
matrix[i][j] = Math.min(
matrix[i - 1][j] + 1, // 删除
matrix[i][j - 1] + 1, // 插入
matrix[i - 1][j - 1] + cost // 替换
);
}
}
return matrix[len1][len2];
}
export const similarity = (str1: string, str2: string) => {
const distance = levenshteinDistance(str1, str2);
const maxLength = Math.max(str1.length, str2.length);
return 1 - distance / maxLength;
}