Edit Distance Levenshtein DP (Go)
Compute the Levenshtein edit distance between two Go strings with insert, delete, and substitute operations.
Code
package main
func editDistance(a, b string) int {
m, n := len(a), len(b)
prev := make([]int, n+1)
for j := 0; j <= n; j++ { prev[j] = j }
for i := 1; i <= m; i++ {
curr := make([]int, n+1); curr[0] = i
for j := 1; j <= n; j++ {
if a[i-1] == b[j-1] { curr[j] = prev[j-1] } else { curr[j] = 1 + min(prev[j], curr[j-1], prev[j-1]) }
}
prev = curr
}
return prev[n]
}What the code does
Edit Distance Levenshtein DP (Go) reduces to the function editDistance.
The cycling part of this snippet is for j := 0; j <= n; j++ { prev[j] = j }.
What to watch for
- Everything it calls is documented as part of the language core.
Applying it
Entry signature: func editDistance(a, b string) int
Statements that matter most here
curr := make([]int, n+1); curr[0] = i
prev := make([]int, n+1)
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.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.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
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `editDistance` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.