-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathsol.js
50 lines (43 loc) · 1.3 KB
/
sol.js
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
/**
* @author MadhavBahl
* @date 31/12/2018
*/
function minEditDist (str1, str2) {
// Initialize the distance matrix with all zeroes
let len1 = str1.length,
len2 = str2.length,
distMatrix = [];
for (let i=0; i<=len2; i++) {
let row = [];
for (let j=0; j<=len1; j++) {
// Initialie the edit distance matrix by all zeroes
row.push(0);
}
distMatrix.push(row);
}
// Fill the first row
for (let i=0; i<=len1; i++) {
distMatrix[0][i] = i;
}
// Fill the first column
for (let j=0; j<=len2; j++) {
distMatrix[j][0] = j;
}
// Fill the edit distance matrix
for (let i=1; i<=len2; i++) {
for (let j=1; j<=len1; j++) {
if (str1[i-1] === str2[j-1]) {
distMatrix[i][j] = distMatrix[i-1][j-1];
} else {
distMatrix [i][j] = 1 + Math.min (
distMatrix[i-1][j-1],
distMatrix[i-1][j],
distMatrix[i][j-1]
);
}
}
}
return distMatrix[len2][len1];
}
console.log(minEditDist ('abcdefgs', 'agced'));
console.log(minEditDist('kitten', 'sitting'));