Skip to content

Commit 35771f2

Browse files
author
sanghaisubham
committed
Updted Edit Distance In Java by adding description
2 parents b7b9443 + acc6f31 commit 35771f2

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

Dynamic Programming/Edit_Distance.java

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,41 @@
11
/**
22
Author : SUBHAM SANGHAI
33
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
64
**/
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+
919
import java.util.Scanner;
1020
public class Edit_Distance
1121
{
22+
23+
24+
1225
public static int minDistance(String word1, String word2)
1326
{
1427
int len1 = word1.length();
1528
int len2 = word2.length();
1629
// len1+1, len2+1, because finally return dp[len1][len2]
1730
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*/
1933
for (int i = 0; i <= len1; i++)
2034
{
2135
dp[i][0] = i;
2236
}
23-
37+
/* If first string is empty, the only option is to
38+
insert all characters of second string into first*/
2439
for (int j = 0; j <= len2; j++)
2540
{
2641
dp[0][j] = j;
@@ -40,6 +55,8 @@ public static int minDistance(String word1, String word2)
4055
}
4156
else
4257
{
58+
/* if two characters are different ,
59+
then take the minimum of the various operations(i.e insertion,removal,substitution)*/
4360
int replace = dp[i][j] + 1;
4461
int insert = dp[i][j + 1] + 1;
4562
int delete = dp[i + 1][j] + 1;
@@ -50,8 +67,11 @@ public static int minDistance(String word1, String word2)
5067
}
5168
}
5269
}
70+
/* return the final answer , after traversing through both the strings*/
5371
return dp[len1][len2];
5472
}
73+
74+
5575
// Driver program to test above function
5676
public static void main(String args[])
5777
{

0 commit comments

Comments
 (0)