UNPKG

lgrthms

Version:

Algorithms and data structures for your JavaScript and TypeScript projects 🧑‍💻

32 lines (31 loc) 1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.levenshteinDistance = void 0; // O(nm) time | O(nm) space function levenshteinDistance(string1, string2) { const table = buildTable(string1, string2); for (let i = 1; i <= string1.length; i++) { for (let j = 1; j <= string2.length; j++) { if (string1[i - 1] === string2[j - 1]) { table[i][j] = table[i - 1][j - 1]; } else { table[i][j] = 1 + Math.min(table[i - 1][j], table[i - 1][j - 1], table[i][j - 1]); } } } return table[string1.length][string2.length]; } exports.levenshteinDistance = levenshteinDistance; function buildTable(string1, string2) { const table = []; for (let i = 0; i <= string1.length; i++) { const row = []; for (let j = 0; j <= string2.length; j++) { row.push(j); } row[0] = i; table.push(row); } return table; }