forked from williamfiset/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditDistance.java
More file actions
72 lines (46 loc) · 1.73 KB
/
Copy pathEditDistance.java
File metadata and controls
72 lines (46 loc) · 1.73 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* An implementation of the edit distance algorithm
*
* Time Complexity: O(nm)
*
* @author Micah Stairs
**/
public class EditDistance {
// Computes the cost to convert a string 'a' into a string 'b' using dynamic
// programming given the insertionCost, deletionCost and substitutionCost, O(nm)
static int editDistance(String a, String b, int insertionCost, int deletionCost, int substitutionCost) {
final int AL = a.length(), BL = b.length();
int[][] arr = new int[AL + 1][BL + 1];
for (int i = 0; i <= AL; i++) {
for (int j = (i == 0 ? 1 : 0); j <= BL; j++) {
int min = Integer.MAX_VALUE;
// Substitution
if (i > 0 && j > 0)
min = arr[i - 1][j - 1] + (a.charAt(i - 1) == b.charAt(j - 1) ? 0 : substitutionCost);
// Deletion
if (i > 0)
min = Math.min(min, arr[i - 1][j] + deletionCost);
// Insertion
if (j > 0)
min = Math.min(min, arr[i][j - 1] + insertionCost);
arr[i][j] = min;
}
}
return arr[AL][BL];
}
public static void main(String[] args) {
String a = "abcdefg"; String b = "abcdefg";
// The strings are the same so the cost is zero
System.out.println( editDistance(a,b,10,10,10) );
a = "aaa"; b = "aaabbb";
// 10*3 = 30 because of three insertions
System.out.println( editDistance(a,b,10, 2, 3));
a = "1023"; b = "10101010";
// Outputs 2*2 + 4*5 = 24 for 2 substitutions and 4 insertions
System.out.println( editDistance(a,b,5,7,2) );
a = "923456789"; b = "12345";
// Outputs 4*4 + 1 = 16 because we need to delete 4
// characters and perform one substitution
System.out.println( editDistance(a,b,2,4,1));
}
}