File tree Expand file tree Collapse file tree 1 file changed +14
-11
lines changed Expand file tree Collapse file tree 1 file changed +14
-11
lines changed Original file line number Diff line number Diff line change @@ -12,31 +12,34 @@ You want to match two or more strings.
12
12
Calculate the edit distance, or number of operations required to transform one string into the other.
13
13
14
14
{% highlight coffeescript %}
15
+
15
16
Levenshtein =
16
17
(str1, str2) ->
17
-
18
+
18
19
l1 = str1.length
19
20
l2 = str2.length
20
-
21
+
21
22
Math.max l1, l2 if Math.min l1, l2 == 0
22
-
23
+
23
24
i = 0; j = 0; distance = []
24
25
25
26
for i in [0...l1 + 1]
26
- distance[i] = []
27
- distance[i][0] = i
27
+ distance[i] = []
28
+ distance[i][0] = i
28
29
29
30
distance[0][j] = j for j in [0...l2 + 1]
30
-
31
+
31
32
for i in [1...l1 + 1]
32
- for j in [1...l2 + 1]
33
- distance[i][j] = Math.min distance[i - 1][j] + 1,
34
- distance[i][j - 1] + 1,
35
- distance[i - 1][j - 1] + if str1.charAt(i - 1) == str2.charAt(j - 1) then 0 else 1
33
+ for j in [1...l2 + 1]
34
+ distance[i][j] = Math.min distance[i - 1][j] + 1,
35
+ distance[i][j - 1] + 1,
36
+ distance[i - 1][j - 1] +
37
+ if (str1.charAt i - 1) == (str2.charAt j - 1) then 0 else 1
36
38
37
39
distance[l1][l2]
40
+
38
41
{% endhighlight %}
39
42
40
43
## Discussion
41
44
42
- You can use either Hirschberg or Wagner–Fischer's algorithm to calculate a Levenshtein distance. This example uses Wagner–Fischer's algorithm.
45
+ You can use either Hirschberg or Wagner–Fischer's algorithm to calculate a Levenshtein distance. This example uses Wagner–Fischer's algorithm.
You can’t perform that action at this time.
0 commit comments