|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +public class Edit_Distance { |
| 4 | + |
| 5 | + /*Edit (Levenshtein Distance) Algorithm |
| 6 | +
|
| 7 | + Problem (informal): Given two strings, find minimum number of deletions, insertions, or replacements required to transform |
| 8 | + |
| 9 | + Algorithm: If characters are same, continue, else, consider removal, deletion, and replacement and consider minimum recursively |
| 10 | + |
| 11 | + Complexity: |
| 12 | + * Time - O(n^2) |
| 13 | + * Space - O(n^2) with memoization and O(1) without |
| 14 | + |
| 15 | + Functions Defined: |
| 16 | + * editDistanceIterative() - Bottom up implementation, finds minimum iteratively |
| 17 | + * editDistanceRecursive() - Top down implementation, recursive |
| 18 | + |
| 19 | + */ |
| 20 | + |
| 21 | + static int[][] dp; |
| 22 | + public static void main(String[] args) { |
| 23 | + String a = "hey if you like this repository, you should give it a star!"; |
| 24 | + String b = "I'd appreciate any feedback or requests -- just fork this repo and add to the README.md"; |
| 25 | + |
| 26 | + dp = new int [a.length()+1][b.length()+1]; |
| 27 | + |
| 28 | + for(int[] row :dp){ |
| 29 | + Arrays.fill(row, -1); |
| 30 | + } |
| 31 | + |
| 32 | + System.out.println(editDistanceIterative(a, b)); |
| 33 | + System.out.println(editDistanceTD(a, b)); |
| 34 | + |
| 35 | + } |
| 36 | + |
| 37 | + public static int editDistanceIterative(String a, String b){ |
| 38 | + int[][] dp = new int[a.length()+1][b.length()+1]; |
| 39 | + for(int i=0; i <= a.length();i++){ |
| 40 | + for(int j=0; j <= b.length();j++){ |
| 41 | + if(i==0 || j==0) |
| 42 | + dp[i][j] = i+j; |
| 43 | + else if(a.charAt(i-1) == b.charAt(j-1)) |
| 44 | + dp[i][j] = dp[i-1][j-1]; |
| 45 | + else |
| 46 | + dp[i][j] = 1 + Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]); |
| 47 | + } |
| 48 | + } |
| 49 | + return dp[a.length()][b.length()]; |
| 50 | + } |
| 51 | + |
| 52 | + //minimal # of insertions, substitutions, deletions required to change String a to b |
| 53 | + public static int editDistanceTD(String a, String b){ |
| 54 | + int m = a.length(); |
| 55 | + int n = b.length(); |
| 56 | + if(dp[m][n] !=-1){ |
| 57 | + return dp[m][n]; |
| 58 | + } |
| 59 | + if(m==0 || n==0){ |
| 60 | + dp[m][n] = m+n; |
| 61 | + return dp[m][n]; |
| 62 | + } |
| 63 | + if(a.charAt(m-1) == b.charAt(n-1)){ |
| 64 | + dp[m][n] = editDistanceTD(a.substring(0, m-1), b.substring(0, n-1)); |
| 65 | + return dp[m][n]; |
| 66 | + } |
| 67 | + dp[m][n] = 1 + Math.min(Math.min(editDistanceTD(a.substring(0, m-1), b), editDistanceTD(a, b.substring(0, n-1))), editDistanceTD(a.substring(0, m-1), b.substring(0, n-1))); |
| 68 | + return dp[m][n]; |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments