@@ -54,23 +54,35 @@ func search(slice []string, substring string) []SearchResult {
5454 }
5555
5656 func levenshteinDistance(s, t string) int {
57+ // Create matrix of size (lenS+1)*(lenT+1)
5758 lenS := len(s)
5859 lenT := len(t)
5960
60- if lenS == 0 {
61- return lenT
61+ // Initialize the matrix
62+ d := make([][]int, lenS+1)
63+ for i := range d {
64+ d[i] = make([]int, lenT+1)
65+ d[i][0] = i // Fill first column
6266 }
63- if lenT == 0 {
64- return lenS
67+ for j := range d[0] {
68+ d[0][j] = j // Fill first row
6569 }
6670
67- if s[lenS-1] == t[lenT-1] {
68- return levenshteinDistance(s[:lenS-1], t[:lenT-1])
71+ // Fill the matrix
72+ for i := 1; i <= lenS; i++ {
73+ for j := 1; j <= lenT; j++ {
74+ cost := 1
75+ if s[i-1] == t[j-1] {
76+ cost = 0
77+ }
78+
79+ d[i][j] = min(
80+ d[i-1][j]+1, // deletion
81+ d[i][j-1]+1, // insertion
82+ d[i-1][j-1]+cost, // substitution
83+ )
84+ }
6985 }
7086
71- return 1 + min(
72- levenshteinDistance(s[:lenS-1], t),
73- levenshteinDistance(s, t[:lenT-1]),
74- levenshteinDistance(s[:lenS-1], t[:lenT-1]),
75- )
87+ return d[lenS][lenT]
7688 }