-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheditdistance.java
52 lines (40 loc) · 1.08 KB
/
editdistance.java
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
package strings;
public class editdistance {
public static void main(String[] args) {
// TODO Auto-generated method stub
// editdistance("abc", "bcd");
editdistance("abc", "abd");
}
public static void editdistance(String s1, String s2) {
int m = s1.length();
int n = s2.length();
int[][] dp = new int[s1.length() + 1][s2.length() + 1];
// filling first row
for (int j = 0; j < dp[0].length; j++) {
dp[0][j] = j;
}
// filling first column
for (int i = 1; i < dp.length; i++) {
dp[i][0] = i;
}
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
int replace = dp[i - 1][j - 1];
int insert = dp[i][j - 1];
int remove = dp[i - 1][j];
dp[i][j] = Math.min(replace, Math.min(remove, insert)) + 1;
}
}
}
// for (int i = 0; i < dp.length; i++) {
// for (int j = 0; j < dp[0].length; j++) {
// System.out.print(dp[i][j] + " ");
// }
// System.out.println();
// }
System.out.println(dp[m][n]);
}
}