fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main(String[] args) {
  11. final Ideone l = new Ideone();
  12. System.out.println(l.calculateLevenshteinDistance("cat", "hat"));
  13. }
  14.  
  15. public int calculateLevenshteinDistance(String first, String second) {
  16.  
  17. char[] s = first.toCharArray();
  18. char[] t = second.toCharArray();
  19. int substitutionCost = 0;
  20.  
  21. int m = first.length();
  22. int n = second.length();
  23.  
  24. int[][] array = new int[m + 1][n + 1];
  25.  
  26. for (int i = 1; i <= m; i++) {
  27. array[i][0] = i;
  28. }
  29.  
  30. for (int j = 1; j <= n; j++) {
  31.  
  32. array[0][j] = j;
  33. }
  34.  
  35. for (int j = 1; j <= n; j++) {
  36. for (int i = 1; i <= m; i++) {
  37. if (s[i - 1] == t[j - 1]) {
  38. substitutionCost = 0;
  39. } else {
  40. substitutionCost = 1;
  41. }
  42.  
  43. int deletion = array[i - 1][j] + 1;
  44. int insertion = array[i][j - 1] + 1;
  45. int substitution = array[i - 1][j - 1] + substitutionCost;
  46. int cost = Math.min(
  47. deletion,
  48. Math.min(
  49. insertion,
  50. substitution));
  51. array[i][j] = cost;
  52. }
  53. }
  54.  
  55. return array[m][n];
  56. }
  57.  
  58. }
Success #stdin #stdout 0.09s 27740KB
stdin
Standard input is empty
stdout
1