Edit Distance Levenshtein DP (Java)

Compute the Levenshtein edit distance between two Java strings with insert, delete, and substitute operations.

JavaData Integrity

Code

javasnippet
13 lines
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];
    }
}

How it works

Count the class EditDistance and the function compute as the entire surface area of Edit Distance Levenshtein DP (Java).

Repetition is confined to for (int j = 0; j <= n; j++) prev[j] = j; — the rest of the file is straight-line.

Using it

The main signature reads public static int compute(String a, String b)

Key statements

return prev[n];

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `compute` at load time.