Chinaunix首页 | 论坛 | 博客
  • 博客访问: 222338
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: Java

2011-08-02 10:20:04

  1. /**
  2.  * Algorithm Implementations in Java
  3.  * created on Jul 29, 2011
  4.  * ended it on Aug 1, 2011
  5.  *
  6.  */
  7. package org.mht.strings;

  8. public class LevenshteinDistance {
  9.     
  10.     public LevenshteinDistance() { }
  11.     
  12.     public static int levenshteinDistance(String source, String target) {
  13.         
  14.         int m = source.length();
  15.         int n = target.length();
  16.         
  17.         int[][] distance = new int[m+1][n+1];
  18.         
  19.         for (int i = 0; i <= m; i++)
  20.             distance[i][0] = i;
  21.         for (int j = 0; j <= n; j++)
  22.             distance[0][j] = j;
  23.         
  24.     //    System.out.println("distance[0][2] is " + distance[0][2]);

  25.         for (int i = 1; i <= m; i++)
  26.             for (int j = 1; j <= n; j++)
  27.                 distance[i][j] = minimum(distance[i-1][j]+1, minimum(distance[i][j-1]+1, distance[i-1][j-1]+
  28.                             ((source.charAt(i-1) == target.charAt((j-1)) ? 0 : 1))));
  29.         return distance[m][n];    
  30.         }
  31.     
  32.     public static int minimum(int dist1, int dist2) {
  33.         if (dist1 >= dist2)
  34.             return dist2;
  35.         else
  36.             return dist1;
  37.         }
  38.     
  39. }///:~

  40. /**
  41.  * Algorithm psudocode from:
  42.  *
  43.  * int LevenshteinDistance(char s[1..m], char t[1..n]){
  44.   // for all i and j, d[i,j] will hold the Levenshtein distance between
  45.   // the first i characters of s and the first j characters of t;
  46.   // note that d has (m+1)x(n+1) values
  47.   declare int d[0..m, 0..n]

  48.   for i from 0 to m
  49.     d[i, 0] := i // the distance of any first string to an empty second string
  50.   for j from 0 to n
  51.     d[0, j] := j // the distance of any second string to an empty first string

  52.   for j from 1 to n
  53.   {
  54.     for i from 1 to m
  55.     {
  56.       d[i, j] := minimum(
  57.                      d[i-1, j] + 1, // a deletion
  58.                      d[i, j-1] + 1, // an insertion
  59.                      d[i-1, j-1] + ? 0 : 1 // a substitution, 0 for same , otherwise 1
  60.                    )
  61.     }
  62.   }

  63.   return d[m,n]
  64. }
  65.  */
阅读(537) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~