mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
go: add «72. Edit Distance»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
bb796ab51f
commit
d36f1554da
1 changed files with 60 additions and 0 deletions
60
go/edit-distance.go
Normal file
60
go/edit-distance.go
Normal file
|
@ -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()
|
||||
}
|
Loading…
Reference in a new issue