61 lines
998 B
Go
61 lines
998 B
Go
|
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()
|
||
|
}
|