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];
}
}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
Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.