Skip to content

Commit 3a6a928

Browse files
committed
Add problem 72 - Edit Distance
1 parent b31395e commit 3a6a928

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package dynamic_programming
2+
3+
func EditDistance(word1 string, word2 string) int {
4+
// Lengths of strings
5+
m, n := len(word1), len(word2)
6+
// Lookup table to store the minimum operations count
7+
lookup := make([][]int, m+1)
8+
for i := range lookup {
9+
lookup[i] = make([]int, n+1)
10+
for j := range lookup[i] {
11+
lookup[i][j] = 0
12+
}
13+
}
14+
// Base initialization
15+
for i := 0; i <= m; i++ {
16+
lookup[i][0] = i
17+
}
18+
for j := 0; j <= n; j++ {
19+
lookup[0][j] = j
20+
}
21+
// Populate the remaining table
22+
for i := 1; i <= m; i++ {
23+
for j := 1; j <= n; j++ {
24+
// If both characters are same, we don't have to do anything
25+
cost := 0
26+
if word1[i-1] != word2[j-1] {
27+
cost = 1
28+
}
29+
lookup[i][j] = min(cost+lookup[i-1][j-1], 1+min(lookup[i-1][j], lookup[i][j-1]))
30+
}
31+
}
32+
return lookup[m][n]
33+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package dynamic_programming_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/anirudhology/leetcode-go/problems/dynamic_programming"
7+
)
8+
9+
func TestMinDistanceEmptyStrings(t *testing.T) {
10+
result := dynamic_programming.EditDistance("", "")
11+
if result != 0 {
12+
t.Errorf("Expected 0, got %d", result)
13+
}
14+
}
15+
16+
func TestMinDistanceOneEmptyString(t *testing.T) {
17+
if result := dynamic_programming.EditDistance("hello", ""); result != 5 {
18+
t.Errorf("Expected 5, got %d", result)
19+
}
20+
if result := dynamic_programming.EditDistance("", "java"); result != 4 {
21+
t.Errorf("Expected 4, got %d", result)
22+
}
23+
}
24+
25+
func TestMinDistanceSameStrings(t *testing.T) {
26+
if result := dynamic_programming.EditDistance("same", "same"); result != 0 {
27+
t.Errorf("Expected 0, got %d", result)
28+
}
29+
}
30+
31+
func TestMinDistanceDifferentStrings(t *testing.T) {
32+
if result := dynamic_programming.EditDistance("horse", "ros"); result != 3 {
33+
t.Errorf("Expected 3, got %d", result)
34+
}
35+
if result := dynamic_programming.EditDistance("intention", "execution"); result != 5 {
36+
t.Errorf("Expected 5, got %d", result)
37+
}
38+
if result := dynamic_programming.EditDistance("flaw", "lawn"); result != 2 {
39+
t.Errorf("Expected 2, got %d", result)
40+
}
41+
}

0 commit comments

Comments
 (0)