1
+ """
2
+ Given two strings, A and B. Find minimum number of edits required to convert
3
+ A to B. Following are the allowed operations(edits) :
4
+
5
+ 1. Insert(Insert a new character before or after any index i of A)
6
+ 2. Remove(Remove the charater at the ith index of A)
7
+ 3. Replace(Replace the character at ith indedx of A to any other character
8
+ (possibly same))
9
+
10
+ Cost of all the operations are equal.
11
+
12
+ Time Complexity : O(M X N)
13
+ Space Complexity : O(M X N), where M and N are the lengths of A and B
14
+ respectively.
15
+ """
16
+
17
+ def edit_distance (str1 , str2 ):
18
+ """
19
+ :param str1: string
20
+ :param str2: string
21
+ :return: int
22
+ """
23
+ m = len (str1 )
24
+ n = len (str2 )
25
+
26
+ # Create a table to store results of subproblems
27
+ dp = [ [0 for x in range (n + 1 )] for x in range (m + 1 ) ]
28
+
29
+ """
30
+ dp[i][j] : contains minimum number of edits to convert str1[0...i] to str2[0...j]
31
+ """
32
+
33
+ # Fill d[][] in bottom up manner
34
+ for i in range (m + 1 ):
35
+ for j in range (n + 1 ):
36
+
37
+ # If first string is empty, only option is to
38
+ # insert all characters of second string
39
+ if i == 0 :
40
+ dp [i ][j ] = j # Min. operations = j
41
+
42
+ # If second string is empty, only option is to
43
+ # remove all characters of second string
44
+ elif j == 0 :
45
+ dp [i ][j ] = i # Min. operations = i
46
+
47
+ # If last characters are same, ignore last char
48
+ # and recur for remaining string
49
+ elif str1 [i - 1 ] == str2 [j - 1 ]:
50
+ dp [i ][j ] = dp [i - 1 ][j - 1 ]
51
+
52
+ # If last character are different, consider all
53
+ # possibilities and find minimum
54
+ else :
55
+ dp [i ][j ] = 1 + min (dp [i ][j - 1 ], # Insert
56
+ dp [i - 1 ][j ], # Remove
57
+ dp [i - 1 ][j - 1 ]) # Replace
58
+
59
+
60
+ return dp [m ][n ]
0 commit comments