Skip to content

Instantly share code, notes, and snippets.

@yeco
Created December 20, 2012 23:15
Show Gist options
  • Select an option

  • Save yeco/4349473 to your computer and use it in GitHub Desktop.

Select an option

Save yeco/4349473 to your computer and use it in GitHub Desktop.
Levenshtein Distance Algorythm
levenshteinDistance = function(str1, str2) {
var l1 = str1.length,
l2 = str2.length;
if(Math.min(l1, l2) === 0) {
return Math.max(l1, l2);
}
var i = 0,
j = 0,
d = [];
for(i = 0; i <= l1; i++) {
d[i] = [];
d[i][0] = i;
}
for(j = 0; j <= l2; j++) {
d[0][j] = j;
}
for(i = 1; i <= l1; i++) {
for(j = 1; j <= l2; j++) {
d[i][j] = Math.min(
d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (str1.charAt(i - 1) === str2.charAt(j - 1) ? 0 : 1));
}
}
return d[l1][l2];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment