編輯距離演算法

bitterteaer發表於2024-03-29
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;
}

相關文章