1
1
/**
2
2
Author : SUBHAM SANGHAI
3
3
A Dynamic Programming based solution for Edit Distance problem In Java
4
- Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another,
5
- by counting the minimum number of operations required to transform one string into the other
6
4
**/
7
- import java .util .HashMap ;
8
- import java .util .Map ;
5
+
6
+ /**Description of Edit Distance with an Example:
7
+
8
+ Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another,
9
+ by counting the minimum number of operations required to transform one string into the other. The
10
+ distance operations are the removal, insertion, or substitution of a character in the string.
11
+
12
+
13
+ The Distance between "kitten" and "sitting" is 3. A minimal edit script that transforms the former into the latter is:
14
+
15
+ kitten → sitten (substitution of "s" for "k")
16
+ sitten → sittin (substitution of "i" for "e")
17
+ sittin → sitting (insertion of "g" at the end).**/
18
+
9
19
import java .util .Scanner ;
10
20
public class Edit_Distance
11
21
{
22
+
23
+
24
+
12
25
public static int minDistance (String word1 , String word2 )
13
26
{
14
27
int len1 = word1 .length ();
15
28
int len2 = word2 .length ();
16
29
// len1+1, len2+1, because finally return dp[len1][len2]
17
30
int [][] dp = new int [len1 + 1 ][len2 + 1 ];
18
-
31
+ /* If second string is empty, the only option is to
32
+ insert all characters of first string into second*/
19
33
for (int i = 0 ; i <= len1 ; i ++)
20
34
{
21
35
dp [i ][0 ] = i ;
22
36
}
23
-
37
+ /* If first string is empty, the only option is to
38
+ insert all characters of second string into first*/
24
39
for (int j = 0 ; j <= len2 ; j ++)
25
40
{
26
41
dp [0 ][j ] = j ;
@@ -40,6 +55,8 @@ public static int minDistance(String word1, String word2)
40
55
}
41
56
else
42
57
{
58
+ /* if two characters are different ,
59
+ then take the minimum of the various operations(i.e insertion,removal,substitution)*/
43
60
int replace = dp [i ][j ] + 1 ;
44
61
int insert = dp [i ][j + 1 ] + 1 ;
45
62
int delete = dp [i + 1 ][j ] + 1 ;
@@ -50,8 +67,11 @@ public static int minDistance(String word1, String word2)
50
67
}
51
68
}
52
69
}
70
+ /* return the final answer , after traversing through both the strings*/
53
71
return dp [len1 ][len2 ];
54
72
}
73
+
74
+
55
75
// Driver program to test above function
56
76
public static void main (String args [])
57
77
{
0 commit comments