Advertisement
Guest User

Untitled

a guest
Dec 1st, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. package util;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class EditDistance {
  6.     // levenshtein distance with dp
  7.  
  8.     private static int costOfSubstitution(char a, char b) {
  9.         return a == b ? 0 : 1;
  10.     }
  11.  
  12.     private static int min(int... numbers) {
  13.         return Arrays.stream(numbers)
  14.                 .min().orElse(Integer.MAX_VALUE);
  15.     }
  16.  
  17.     private static int calculateRecursive(String x, String y) {
  18.         if (x.isEmpty()) {
  19.             return y.length();
  20.         }
  21.  
  22.         if (y.isEmpty()) {
  23.             return x.length();
  24.         }
  25.  
  26.         int substitution = calculate(x.substring(1), y.substring(1))
  27.                 + costOfSubstitution(x.charAt(0), y.charAt(0));
  28.         int insertion = calculate(x, y.substring(1)) + 1;
  29.         int deletion = calculate(x.substring(1), y) + 1;
  30.  
  31.         return min(substitution, insertion, deletion);
  32.     }
  33.  
  34.  
  35.     public static int calculate(String x, String y) {
  36.         int[][] dp = new int[x.length() + 1][y.length() + 1];
  37.  
  38.         for (int i = 0; i <= x.length(); i++) {
  39.             for (int j = 0; j <= y.length(); j++) {
  40.                 if (i == 0) {
  41.                     dp[i][j] = j;
  42.                 }
  43.                 else if (j == 0) {
  44.                     dp[i][j] = i;
  45.                 }
  46.                 else {
  47.                     dp[i][j] = min(dp[i - 1][j - 1]
  48.                                     + costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)),
  49.                             dp[i - 1][j] + 1,
  50.                             dp[i][j - 1] + 1);
  51.                 }
  52.             }
  53.         }
  54.  
  55.         return dp[x.length()][y.length()];
  56.     }
  57.  
  58.     public static void main(String[] args) {
  59.         System.out.println(calculate("kitten", "sitting"));
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement