编辑距离算法

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;
}
posted @ 2024-03-29 11:42  bitterteaer  阅读(4)  评论(0编辑  收藏  举报