Edit Distance Levenshtein DP (Java)
Compute the Levenshtein edit distance between two Java strings with insert, delete, and substitute operations.
Code
public class EditDistance {
public static int compute(String a, String b) {
int m = a.length(), n = b.length();
int[] prev = new int[n + 1];
for (int j = 0; j <= n; j++) prev[j] = j;
for (int i = 1; i <= m; i++) {
int[] curr = new int[n + 1]; curr[0] = i;
for (int j = 1; j <= n; j++) { if (a.charAt(i - 1) == b.charAt(j - 1)) curr[j] = prev[j - 1]; else curr[j] = 1 + Math.min(Math.min(prev[j], curr[j - 1]), prev[j - 1]); }
prev = curr;
}
return prev[n];
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.