Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a26cf93

Browse files
committed
optimized levenstein distance algorithm...
- replaced the recursive implementation with iterative - used one-dimensional array for memoizing single row(the previous one) of the distance matrix at iteration
1 parent b535188 commit a26cf93

File tree

1 file changed

+24
-14
lines changed

1 file changed

+24
-14
lines changed

src/others/levenshtein-distance.js

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,31 @@
33

44
var levenshteinDistance = (function () {
55

6-
function levenshteinDistance(s, ls, t, lt) {
7-
if (ls === 0) {
8-
return lt;
9-
}
10-
if (lt === 0) {
11-
return ls;
6+
function levenshteinDistance (s, ls, t, lt) {
7+
var memo = [];
8+
var currRowMemo;
9+
var i;
10+
var k;
11+
12+
for (k = 0; k <= lt; k += 1) {
13+
memo[k] = k;
1214
}
13-
var cost;
14-
if (s[ls - 1] === t[lt - 1]) {
15-
cost = 0;
16-
} else {
17-
cost = 1;
15+
16+
for (i = 1; i <= ls; i += 1) {
17+
currRowMemo = [i];
18+
19+
for (k = 1; k <= lt; k += 1) {
20+
currRowMemo[k] = Math.min(
21+
currRowMemo[k - 1] + 1,
22+
memo[k] + 1,
23+
memo[k - 1] + (s[i - 1] !== t[k - 1] ? 1 : 0)
24+
);
25+
}
26+
27+
memo = currRowMemo;
1828
}
19-
return Math.min(levenshteinDistance(s, ls - 1, t, lt) + 1,
20-
levenshteinDistance(s, ls, t, lt - 1) + 1,
21-
levenshteinDistance(s, ls - 1, t, lt - 1) + cost);
29+
30+
return memo[lt];
2231
}
2332

2433
/**
@@ -49,3 +58,4 @@
4958
exports.levenshteinDistance = levenshteinDistance;
5059

5160
}(typeof exports === 'undefined' ? window : exports));
61+

0 commit comments

Comments
 (0)