Skip to content

Instantly share code, notes, and snippets.

@danielrobertson
Created October 13, 2015 03:31
Show Gist options
  • Save danielrobertson/614a790a3e0a2e1d6d5f to your computer and use it in GitHub Desktop.
Save danielrobertson/614a790a3e0a2e1d6d5f to your computer and use it in GitHub Desktop.
Edit Distance
int getEditDistance(String a, String b) {
int[][] distances = new int[a.length()][b.length()];
for(int i = 0; i < distances.length; i++) {
distances[i][0] = i;
}
for(int j = 0; j < distances[0].length; j++) {
distances[0][j] = j;
}
for(int i = 1; i < a.length(); i++) {
for(int j = 1; j < b.length(); j++) {
int dist1 = distances[i - 1][j - 1];
if(a.charAt(i) != b.charAt(j)) {
dist1 += 2;
}
int dist2 = distances[i - 1][j] + 1;
int dist3 = distances[i][j - 1] + 1;
distances[i][j] = Math.min(dist1, Math.min(dist2, dist3));
}
}
return distances[a.length() - 1][b.length() - 1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment