|
| 1 | +/** |
| 2 | + * |
| 3 | + * @author Kshitij VERMA (github.com/kv19971) |
| 4 | + * LEVENSHTEIN DISTANCE dyamic programming implementation to show the difference between two strings (https://en.wikipedia.org/wiki/Levenshtein_distance) |
| 5 | + * |
| 6 | + * |
| 7 | + */ |
| 8 | + |
| 9 | +public class Levenshtein_distance{ |
| 10 | + private int minimum(int a, int b, int c){ |
| 11 | + if(a < b && a < c){ |
| 12 | + return a; |
| 13 | + }else if(b < a && b < c){ |
| 14 | + return b; |
| 15 | + }else{ |
| 16 | + return c; |
| 17 | + } |
| 18 | + } |
| 19 | + public int calculate_distance(String a, String b){ |
| 20 | + len_a = a.length() + 1; |
| 21 | + len_b = b.length() + 1; |
| 22 | + int [][] distance_mat = new int[len_a][len_b]; |
| 23 | + for(int i = 0; i < len_a; i++){ |
| 24 | + distance_mat[i][0] = i; |
| 25 | + } |
| 26 | + for(int j = 0; j < len_b; j++){ |
| 27 | + distance_mat[0][j] = j; |
| 28 | + } |
| 29 | + for(int i = 0; i < len_a; i++){ |
| 30 | + for(int j = 0; i < len_b; j++){ |
| 31 | + int cost; |
| 32 | + if (a.charAt(i) == b.charAt(j)){ |
| 33 | + cost = 0; |
| 34 | + }else{ |
| 35 | + cost = 1; |
| 36 | + } |
| 37 | + distance_mat[i][j] = minimum(distance_mat[i-1][j], distance_mat[i-1][j-1], distance_mat[i][j-1]) + cost; |
| 38 | + |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + } |
| 43 | + return distance_mat[len_a-1][len_b-1]; |
| 44 | + |
| 45 | + } |
| 46 | + public static void main(String [] args){ |
| 47 | + String a = ""; // enter your string here |
| 48 | + String b = ""; // enter your string here |
| 49 | + |
| 50 | + System.out.print("Levenshtein distance between "+a + " and "+b+ " is: "); |
| 51 | + System.out.println(calculate_distance(a,b)); |
| 52 | + |
| 53 | + |
| 54 | + } |
| 55 | +} |
0 commit comments