File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-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+ Levenshtein =
16+ (str1, str2) ->
17+
18+ l1 = str1.length
19+ l2 = str2.length
20+
21+ Math.max l1, l2 if Math.min l1, l2 == 0
22+
23+ i = 0; j = 0; distance = [ ]
24+
25+ for i in [0...l1 + 1]
26+ distance[i] = []
27+ distance[i][0] = i
28+
29+ distance[0][j] = j for j in [0...l2 + 1]
30+
31+ 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
36+
37+ distance[l1][l2]
38+ {% endhighlight %}
39+
40+ ## Discussion
41+
42+ 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