Skip to content

Instantly share code, notes, and snippets.

@Jimexist
Last active December 20, 2015 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jimexist/6089426 to your computer and use it in GitHub Desktop.
Save Jimexist/6089426 to your computer and use it in GitHub Desktop.
Edit distance using DP
public class Solution {
private static final int MATCHED = 1, DELETED = 1, INSERTED = 1;
public int minDistance(String word1, String word2) {
if (word1.length() == 0) return word2.length() * INSERTED;
if (word2.length() == 0) return word1.length() * DELETED;
if (word1.equals(word2)) return 0; // not much used though
final int rows = word1.length();
final int cols = word2.length();
final int[][] table = new int[rows + 1][cols + 1];
for (int i=1; i<=cols; ++i) table[0][i] = i;
for (int i=1; i<=rows; ++i) table[i][0] = i;
for (int i=1; i<=rows; ++i) {
for (int j=1; j<=cols; ++j) {
final int matched;
if (word1.charAt(i-1) == word2.charAt(j-1)) {
matched = table[i-1][j-1];
} else {
matched = table[i-1][j-1] + MATCHED;
}
final int delete = table[i-1][j] + DELETED;
final int insert = table[i][j-1] + INSERTED;
table[i][j] = Math.min(matched, Math.min(delete, insert));
}
}
return table[rows][cols];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment