Skip to content

Instantly share code, notes, and snippets.

@christianscott
Created July 3, 2019 15:20
Show Gist options
  • Save christianscott/cbdf2e39983d255e7c5ccc9258407f6d to your computer and use it in GitHub Desktop.
Save christianscott/cbdf2e39983d255e7c5ccc9258407f6d to your computer and use it in GitHub Desktop.
Levenshtein edit distance solution using DP
const COLLATOR = Intl.Collator('generic', {sensitivity: 'base'})
export function levenshteinEditDistance(
source: string,
target: string,
): number {
if (source.length === 0 || target.length === 0) {
return 0
}
// [0, ..., N]
const previousRow = new Array<number>(target.length + 1)
for (let i = 0; i < target.length + 1; i++) {
previousRow[i] = i
}
previousRow[target.length] = target.length
for (let i = 0; i < source.length; i++) {
let nextDistance = i + 1
for (let j = 0; j < target.length; j++) {
let currentDistance = nextDistance
const areCharCodesEqual =
COLLATOR.compare(source.charAt(i), target.charAt(j)) === 0
const distanceIfSubstitute = previousRow[j] + (areCharCodesEqual ? 0 : 1)
const distanceIfInsert = currentDistance + 1
const distanceIfDelete = previousRow[j + 1] + 1
nextDistance = Math.min(
distanceIfSubstitute,
distanceIfInsert,
distanceIfDelete,
)
previousRow[j] = currentDistance
}
previousRow[target.length] = nextDistance
}
return previousRow[target.length]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment