-
Notifications
You must be signed in to change notification settings - Fork 0
/
EditDistance.java
33 lines (28 loc) · 1 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
import java.util.Scanner;
public class EditDistance {
public static int editDistance(String s, String t) {
int[][] dp = new int[s.length() + 1][t.length() + 1];
for (int i = 0; i <= s.length(); i++) {
for (int j = 0; j <= t.length(); j++) {
if (i == 0) {
dp[i][j] = j;
} else if (j == 0) {
dp[i][j] = i;
} else {
if (i>=1 && j>=1 && s.charAt(i-1) == t.charAt(j-1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
}
}
}
}
return dp[s.length()][t.length()];
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String s = scan.next();
String t = scan.next();
System.out.println(editDistance(s, t));
}
}