Edit Distance Levenshtein DP (Go)

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

GoData Integrity

Code

gosnippet
15 lines
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

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.