public class EditDistance {
public static void main(String[] args) {
String word1 = "horse";
String word2 = "ros";
System.out.println(minDistance(word1, word2));
}
public static int minDistance(String word1, String word2) {
if (word1 == null && word2 == null) {
return 0;
}
if (word1 == null) {
return word2.length();
}
if (word2 == null) {
return word1.length();
}
int len1 = word1.length();
int len2 = word2.length();
int[][] dp = new int[len1 + 1][len2 + 1];
// length of word1 is i, word2 is 0, update the edit distance
for (int i = 0; i <= len1; i++) {
dp[i][0] = i;
}
// length of word2 is i, word1 is 0, update the edit distance
for (int j = 0; j <= len2; j++) {
dp[0][j] = j;
}
for (int i = 1; i <= len1; i++) {
// Assume word1's length is i, work out the edit distance when j is 1,2,3,...len2 respectively.
for (int j = 1; j <= len2; j++) {
// Following operations can be considered as calculating edit distance from word1[0:i-1] to
// word2[0:j-1]
// what if we delete the last char of word1[0:i-1], then we adopt the edit distance from
// word1[0:i-2] to word2[j-1]
int del = dp[i - 1][j] + 1;
// what if we delete the last char of word2[0:j-1], then we adopt the edit distance from
// word1[0:i-1] to word2[j-2]
int ins = dp[i][j - 1] + 1;
// what if we replace word1[i-1] with word2[j-1] if not the same, then we adopt the edit distance
// from word1[0:i-2] to word2[j-2]
int rep = dp[i - 1][j - 1];
// No need to change if the last char is the same, following i-1 and j-1 is the index, the
// actual meaning is the ith char in word1 and jth char in word2.
if (word1.charAt(i - 1) != word2.charAt(j - 1)) {
rep += 1;
}
dp[i][j] = min(del, ins, rep);
}
}
return dp[len1][len2];
}
private static int min(int x, int y, int z) {
int min = Math.min(x, y);
return Math.min(min, z);
}
}