File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ ---
2+ layout : recipe
3+ title : Matching Strings
4+ chapter : Strings
5+ ---
6+ ## Problem
7+
8+ You want to match two or more strings.
9+
10+ ## Solution
11+
12+ Calculate the edit distance, or number of operations required to transform one string into the other.
13+
14+ {% highlight coffeescript %}
15+
16+ Levenshtein =
17+ (str1, str2) ->
18+
19+ l1 = str1.length
20+ l2 = str2.length
21+
22+ Math.max l1, l2 if Math.min l1, l2 == 0
23+
24+ i = 0; j = 0; distance = []
25+
26+ for i in [0...l1 + 1]
27+ distance[i] = []
28+ distance[i][0] = i
29+
30+ distance[0][j] = j for j in [0...l2 + 1]
31+
32+ for i in [1...l1 + 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
38+
39+ distance[l1][l2]
40+
41+ {% endhighlight %}
42+
43+ ## Discussion
44+
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