Delphi的实现方法,写了百分比的函数 。。。【注意form1,直接复制要改代码】
function Form1.Levenshtein_Distance(str1: string; str2: string): Double;
begin
d := 0;
if (str1.Length > str2.Length) then
d := str1.Length
else
d := str2.Length;
begin
Result := (1 - ((self.LD(str1, str2) as Double) div (d as Double)));
exit
end
end;
function Form1.LD(s: string; t: string): Integer;
var
i: Integer;
cost: Integer;
begin
n := Strings.Len(s);
m := Strings.Len(t);
if (n = 0) then
begin
Result := m;
exit
end;
if (m = 0) then
begin
Result := n;
exit
end;
dis := New(array[(n + 1), (m + 1)] of Integer);
VB$t_i4$L0 := n;
i := 0;
while ((i <= VB$t_i4$L0)) do
begin
dis[i, 0] := i;
inc(i)
end;
VB$t_i4$L1 := m;
j := 0;
while ((j <= VB$t_i4$L1)) do
begin
dis[0, j] := j;
inc(j)
end;
VB$t_i4$L2 := n;
i := 1;
while ((i <= VB$t_i4$L2)) do
begin
s_i := Strings.Mid(s, i, 1);
VB$t_i4$L3 := m;
j := 1;
while ((j <= VB$t_i4$L3)) do
begin
t_j := Strings.Mid(t, j, 1);
if (s_i = t_j) then
cost := 0
else
cost := 1;
dis[i, j] := self.Minimum((dis[(i - 1), j] + 1), (dis[i, (j - 1)] + 1), (dis[(i - 1), (j - 1)] + cost));
inc(j)
end;
inc(i)
end;
LD := dis[n, m];
dis := nil;
begin
Result := LD;
exit
end
end;
function Form1.Minimum(a: Integer; b: Integer; c: Integer): Integer;
begin
min := a;
if (b < min) then
min := b;
if (c < min) then
min := c;
begin
Result := min;
exit
end
end;