Skip to content

added levenshtein distance dp implementation #101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 28, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions Dynamic Programming/Levenshtein_distance.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
*
* @author Kshitij VERMA (github.com/kv19971)
* LEVENSHTEIN DISTANCE dyamic programming implementation to show the difference between two strings (https://en.wikipedia.org/wiki/Levenshtein_distance)
*
*
*/

public class Levenshtein_distance{
private int minimum(int a, int b, int c){
if(a < b && a < c){
return a;
}else if(b < a && b < c){
return b;
}else{
return c;
}
}
public int calculate_distance(String a, String b){
len_a = a.length() + 1;
len_b = b.length() + 1;
int [][] distance_mat = new int[len_a][len_b];
for(int i = 0; i < len_a; i++){
distance_mat[i][0] = i;
}
for(int j = 0; j < len_b; j++){
distance_mat[0][j] = j;
}
for(int i = 0; i < len_a; i++){
for(int j = 0; i < len_b; j++){
int cost;
if (a.charAt(i) == b.charAt(j)){
cost = 0;
}else{
cost = 1;
}
distance_mat[i][j] = minimum(distance_mat[i-1][j], distance_mat[i-1][j-1], distance_mat[i][j-1]) + cost;


}

}
return distance_mat[len_a-1][len_b-1];

}
public static void main(String [] args){
String a = ""; // enter your string here
String b = ""; // enter your string here

System.out.print("Levenshtein distance between "+a + " and "+b+ " is: ");
System.out.println(calculate_distance(a,b));


}
}