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]
}Report a problem with this exampleOpens a pre-filled issue on GitHub.