levenshtein.js
1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
Copyright (c) 2006. All Rights reserved.
If you use this script, please email me and let me know, thanks!
Andrew Hedges
andrew (at) hedges (dot) name
If you want to hire me to write JavaScript for you, see my resume.
http://andrew.hedges.name/resume/
*/
// return the smallest of the three values passed in
function minimum (x, y, z)
{
if (x < y && x < z) return x;
if (y < x && y < z) return y;
return z;
}
// calculate the Levenshtein distance between a and b,
function levenshtein (a, b)
{
var cost;
var m = a.length;
var n = b.length;
// make sure a.length >= b.length to use O(min(n,m)) space
if (m < n)
{
var c=a; a=b; b=c;
var o=m; m=n; n=o;
}
var r = new Array();
r[0] = new Array();
for (var c = 0; c < n+1; c++)
r[0][c] = c;
for (var i = 1; i < m+1; i++)
{
r[i] = new Array();
r[i][0] = i;
for (var j = 1; j < n+1; j++)
{
cost = (a.charAt(i-1) == b.charAt(j-1))? 0: 1;
r[i][j] = minimum (r[i-1][j]+1, r[i][j-1]+1, r[i-1][j-1]+cost);
}
}
return r[r.length-1][r[r.length-1].length-1];
}