delphi KMP(字符串匹配)算法


本文整理自网络,侵删。

 
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    //模式数组
    arrNext : array of Integer;
    //主串数组
    Schars : array of AnsiChar;
    //字串数组
    Dchars : array of AnsiChar;

    //获取模式数组
    procedure GetNext;
    //查找匹配
    function KPM(sPos:Integer):integer;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.GetNext;
var
  len,m,n:Integer;
begin
  m := 0;
  n := -1;
  len := Length(Dchars);
  SetLength(arrNext,len);
  arrNext[0] := -1;
  while (m+1)<= len do
  begin
    if (n = -1) or (Dchars[m] = Dchars[n]) then
    begin
      Inc(m);
      Inc(n);
      if (Dchars[m] <> Dchars[n]) then
        arrNext[m] := n
      else
        arrNext[m] := arrNext[n];
    end
    else
    begin
      n := arrNext[n];
    end;
  end;
end;

function TForm1.KPM(sPos:Integer): integer;
var
  i,j:Integer;
begin
  Result := 0;
  i := sPos;
  j := 0;
  while (i < Length(Schars)) and (j < Length(Dchars)) do
  begin
    if (Schars[i] = Dchars[j]) then
    begin
      Inc(i);
      Inc(j);
    end
    else
    begin
      Result := Result + j - arrNext[j];
      if arrNext[j] <> -1 then
      begin
        j := arrNext[j];
      end
      else
      begin
        j := 0;
        Inc(i);
      end;
    end;
  end;
  if j <> Length(Dchars) then
    Result := -1;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  s,d:string;
  index : Integer;
begin
  s := '中华人民共和国';
  d := '人民';
  index := -1;
  SetLength(Schars,Length(s));
  SetLength(Dchars,Length(d));
  Move(s[1],Schars[0],Length(s));
  Move(d[1],Dchars[0],Length(d));
  GetNext;
  index := KPM(0);
  if index = -1 then
    ShowMessage('没有找到匹配!')
  else
    ShowMessage('从第'+IntToStr(index+1)+'个字符开始匹配');
end;

end.

相关阅读 >>

Delphi indy 10tidftp中的directorylisting使用

Delphi 调用sql和mysql存储过程

Delphi exe图标替换

Delphi 让子窗体显示最大化

Delphi windows 编程[2] - 学习窗体生成的过程二

Delphi getcomputername() getusername() 获取本机当前用户名

Delphi debug release区别是什么?

Delphi xe5实现的一个阳历转换成阴历的代码

Delphi 简单的倒计时算法

Delphi调试技巧

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...