当前位置:  开发笔记 > 编程语言 > 正文

你如何在德尔福实现Levenshtein距离?

如何解决《你如何在德尔福实现Levenshtein距离?》经验,为你挑选了1个好方法。

我是在回答你自己的问题的精神发表这篇文章的.

我的问题是:如何在Delphi中实现Levenshtein算法来计算两个字符串之间的编辑距离,如此处所述?

只是关于性能的说明:这件事非常快.在我的桌面上(2.33 Ghz双核,2GB内存,WinXP),我可以在不到一秒的时间内完成100K字符串的数组运行.



1> JosephStyons..:
function EditDistance(s, t: string): integer;
var
  d : array of array of integer;
  i,j,cost : integer;
begin
  {
  Compute the edit-distance between two strings.
  Algorithm and description may be found at either of these two links:
  http://en.wikipedia.org/wiki/Levenshtein_distance
  http://www.google.com/search?q=Levenshtein+distance
  }

  //initialize our cost array
  SetLength(d,Length(s)+1);
  for i := Low(d) to High(d) do begin
    SetLength(d[i],Length(t)+1);
  end;

  for i := Low(d) to High(d) do begin
    d[i,0] := i;
    for j := Low(d[i]) to High(d[i]) do begin
      d[0,j] := j;
    end;
  end;

  //store our costs in a 2-d grid  
  for i := Low(d)+1 to High(d) do begin
    for j := Low(d[i])+1 to High(d[i]) do begin
      if s[i] = t[j] then begin
        cost := 0;
      end
      else begin
        cost := 1;
      end;

      //to use "Min", add "Math" to your uses clause!
      d[i,j] := Min(Min(
                 d[i-1,j]+1,      //deletion
                 d[i,j-1]+1),     //insertion
                 d[i-1,j-1]+cost  //substitution
                 );
    end;  //for j
  end;  //for i

  //now that we've stored the costs, return the final one
  Result := d[Length(s),Length(t)];

  //dynamic arrays are reference counted.
  //no need to deallocate them
end;


[Wouter van Nifterick](http://stackoverflow.com/users/38813/wouter-van-nifterick)做了一个更优化的功能[这里](http://stackoverflow.com/a/10593797/576719).
推荐阅读
mobiledu2402851173
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有