/src/org/ooc/frontend/Levenshtein.java

http://github.com/nddrylliog/ooc · Java · 98 lines · 53 code · 28 blank · 17 comment · 13 complexity · 37de4e6fd8fdee164fbdb2ae1fa5c161 MD5 · raw file

  1. package org.ooc.frontend;
  2. /**
  3. * Computes the Levenshtein distance between two strings
  4. * @author Michael Gilleland
  5. */
  6. public class Levenshtein {
  7. // ****************************
  8. // Get minimum of three values
  9. // ****************************
  10. protected static int min(int a, int b, int c) {
  11. int mi;
  12. mi = a;
  13. if (b < mi) {
  14. mi = b;
  15. }
  16. if (c < mi) {
  17. mi = c;
  18. }
  19. return mi;
  20. }
  21. // *****************************
  22. // Compute Levenshtein distance
  23. // *****************************
  24. public static int distance(String s, String t) {
  25. int d[][]; // matrix
  26. int n; // length of s
  27. int m; // length of t
  28. int i; // iterates through s
  29. int j; // iterates through t
  30. char s_i; // ith character of s
  31. char t_j; // jth character of t
  32. int cost; // cost
  33. // Step 1
  34. n = s.length();
  35. m = t.length();
  36. if (n == 0) {
  37. return m;
  38. }
  39. if (m == 0) {
  40. return n;
  41. }
  42. d = new int[n + 1][m + 1];
  43. // Step 2
  44. for (i = 0; i <= n; i++) {
  45. d[i][0] = i;
  46. }
  47. for (j = 0; j <= m; j++) {
  48. d[0][j] = j;
  49. }
  50. // Step 3
  51. for (i = 1; i <= n; i++) {
  52. s_i = s.charAt(i - 1);
  53. // Step 4
  54. for (j = 1; j <= m; j++) {
  55. t_j = t.charAt(j - 1);
  56. // Step 5
  57. if (s_i == t_j) {
  58. cost = 0;
  59. } else {
  60. cost = 1;
  61. }
  62. // Step 6
  63. d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1,
  64. d[i - 1][j - 1] + cost);
  65. }
  66. }
  67. // Step 7
  68. return d[n][m];
  69. }
  70. }