Updted Edit Distance In Java by adding description

This commit is contained in:
sanghaisubham
2017-10-19 18:22:47 +05:30

View File

@ -1,26 +1,41 @@
/** /**
Author : SUBHAM SANGHAI Author : SUBHAM SANGHAI
A Dynamic Programming based solution for Edit Distance problem In Java A Dynamic Programming based solution for Edit Distance problem In Java
Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another,
by counting the minimum number of operations required to transform one string into the other
**/ **/
import java.util.HashMap;
import java.util.Map; /**Description of Edit Distance with an Example:
Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another,
by counting the minimum number of operations required to transform one string into the other. The
distance operations are the removal, insertion, or substitution of a character in the string.
The Distance between "kitten" and "sitting" is 3. A minimal edit script that transforms the former into the latter is:
kitten → sitten (substitution of "s" for "k")
sitten → sittin (substitution of "i" for "e")
sittin → sitting (insertion of "g" at the end).**/
import java.util.Scanner; import java.util.Scanner;
public class Edit_Distance public class Edit_Distance
{ {
public static int minDistance(String word1, String word2) public static int minDistance(String word1, String word2)
{ {
int len1 = word1.length(); int len1 = word1.length();
int len2 = word2.length(); int len2 = word2.length();
// len1+1, len2+1, because finally return dp[len1][len2] // len1+1, len2+1, because finally return dp[len1][len2]
int[][] dp = new int[len1 + 1][len2 + 1]; int[][] dp = new int[len1 + 1][len2 + 1];
/* If second string is empty, the only option is to
insert all characters of first string into second*/
for (int i = 0; i <= len1; i++) for (int i = 0; i <= len1; i++)
{ {
dp[i][0] = i; dp[i][0] = i;
} }
/* If first string is empty, the only option is to
insert all characters of second string into first*/
for (int j = 0; j <= len2; j++) for (int j = 0; j <= len2; j++)
{ {
dp[0][j] = j; dp[0][j] = j;
@ -40,6 +55,8 @@
} }
else else
{ {
/* if two characters are different ,
then take the minimum of the various operations(i.e insertion,removal,substitution)*/
int replace = dp[i][j] + 1; int replace = dp[i][j] + 1;
int insert = dp[i][j + 1] + 1; int insert = dp[i][j + 1] + 1;
int delete = dp[i + 1][j] + 1; int delete = dp[i + 1][j] + 1;
@ -50,8 +67,11 @@
} }
} }
} }
/* return the final answer , after traversing through both the strings*/
return dp[len1][len2]; return dp[len1][len2];
} }
// Driver program to test above function // Driver program to test above function
public static void main(String args[]) public static void main(String args[])
{ {