-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path583.go
More file actions
34 lines (32 loc) · 741 Bytes
/
583.go
File metadata and controls
34 lines (32 loc) · 741 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
func minDistance(word1 string, word2 string) int {
dp := make([][]int, len(word1)+1)
for i := range dp {
dp[i] = make([]int, len(word2)+1)
}
for i := 1; i <= len(word1); i++ {
dp[i][0] = i
}
for j := 1; j <= len(word2); j++ {
dp[0][j] = j
}
for i := 1; i <= len(word1); i++ {
for j := 1; j <= len(word2); j++ {
if word1[i-1] == word2[j-1] {
dp[i][j] = dp[i-1][j-1]
} else {
if dp[i-1][j-1]+2 < dp[i-1][j]+1 {
if dp[i-1][j-1]+2 < dp[i][j-1]+1 {
dp[i][j] = dp[i-1][j-1] + 2
} else {
dp[i][j] = dp[i][j-1] + 1
}
} else if dp[i-1][j]+1 < dp[i][j-1]+1 {
dp[i][j] = dp[i-1][j] + 1
} else {
dp[i][j] = dp[i][j-1] + 1
}
}
}
}
return dp[len(word1)][len(word2)]
}