以下是我根据 LCS 最长公共子串算法实现 C# http://7422.blog.163.com/blog/static/3364459720085179541550/
改写的一段delphi
能执行,运行结果如下:
例如: str1:='中华人民共和国是我家'      str2:='中华人民'  能正确返回 4 说明结果正确。
但 如果 我把str2:='共和国';  则返回 2.  测试结果说明:当字符串2是从第一个字符开始相等则能正确返回最大值。否则返回的最大字符串数将比正确的个数 少1. 我看了半天没有找到原因,望路过的朋友帮忙看看,我到底哪里出了问题。附录上我改的代码:function LCS(str1,str2:widestring):integer;
  var
    maxtix:array of integer;
    i,j:integer;
    maxlength,str1num,str2num:integer;
  begin
    maxLength:=0;
    str1num:=Length(str1);
    str2num:=Length(str2);    if (str1=str2) then
    begin
       result:=str1num;
       exit;
    end;    if ((str1num=0) or (str2num=0)) then
     begin
        Result:=0;
        Exit;
     end;    SetLength(maxtix,str1num+1);
  
   for i:=0 to str2num-1 do
   begin
       for j:=str1num-1 downto 0 do
       begin
           if (str2[i]=str1[j]) then
           begin
                if ((i=0) or (j=0)) then maxtix[j]:=1 else maxtix[j] :=maxtix[j-1] + 1;
           end else begin
               maxtix[j] := 0;
           end;           if (maxtix[j] > maxLength) then
           begin
               maxLength := maxtix[j];
           end;       end;    //end of j:=str1num-1 to 0 do   end;   // end of i:=0 to str2num do  Result:=maxLength;     end;