diff --git a/go/edit-distance.go b/go/edit-distance.go new file mode 100644 index 0000000..65c1f20 --- /dev/null +++ b/go/edit-distance.go @@ -0,0 +1,60 @@ +package main + +const UNSET int = -1 + +type Solver struct { + word1 string + word2 string + dp [][]int +} + +func makeSolver(word1, word2 string) Solver { + dp := make([][]int, len(word1)) + for i := range len(word1) { + dp[i] = make([]int, len(word2)) + for j := range len(word2) { + dp[i][j] = UNSET + } + } + + return Solver{ + word1: word1, + word2: word2, + dp: dp, + } +} + +func (s *Solver) solve(i, j int) int { + if i >= len(s.word1) { + return len(s.word2) - j + } + + if j >= len(s.word2) { + return len(s.word1) - i + } + + if s.dp[i][j] != UNSET { + return s.dp[i][j] + } + + if s.word1[i] == s.word2[j] { + s.dp[i][j] = s.solve(i+1, j+1) + } else { + inserting := 1 + s.solve(i, j+1) + deleting := 1 + s.solve(i+1, j) + replacing := 1 + s.solve(i+1, j+1) + + s.dp[i][j] = min(inserting, min(deleting, replacing)) + } + + return s.dp[i][j] +} + +func (s *Solver) Solve() int { + return s.solve(0, 0) +} + +func minDistance(word1 string, word2 string) int { + solver := makeSolver(word1, word2) + return solver.Solve() +}