levenshtein.go 828 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package utils
  3. import (
  4. "fmt"
  5. "strings"
  6. )
  7. var _ = fmt.Print
  8. // compares two strings and returns the Levenshtein distance between them.
  9. func LevenshteinDistance(s, t string, ignore_case bool) int {
  10. if ignore_case {
  11. s = strings.ToLower(s)
  12. t = strings.ToLower(t)
  13. }
  14. d := make([][]int, len(s)+1)
  15. for i := range d {
  16. d[i] = make([]int, len(t)+1)
  17. }
  18. for i := range d {
  19. d[i][0] = i
  20. }
  21. for j := range d[0] {
  22. d[0][j] = j
  23. }
  24. for j := 1; j <= len(t); j++ {
  25. for i := 1; i <= len(s); i++ {
  26. if s[i-1] == t[j-1] {
  27. d[i][j] = d[i-1][j-1]
  28. } else {
  29. min := d[i-1][j]
  30. if d[i][j-1] < min {
  31. min = d[i][j-1]
  32. }
  33. if d[i-1][j-1] < min {
  34. min = d[i-1][j-1]
  35. }
  36. d[i][j] = min + 1
  37. }
  38. }
  39. }
  40. return d[len(s)][len(t)]
  41. }