Delphi实现的Sunday字符串搜索算法

type
  TBMKey=record
    Length:Integer;
    Offsets:array[0..255] of Integer;
    ps:PAnsiChar;
  end;
procedure InitKeyDistance(var AKey:TBMKey);
var
  I:Integer;
begin
AKey.Length:=StrLen(AKey.ps);
for I := 0 to 255 do
  AKey.Offsets[I]:=AKey.Length;
for I := 0 to AKey.Length-1 do
  AKey.Offsets[Ord(AKey.ps[I])]:=AKey.Length-I-1;
end;
function SundayStrStrA(s:PAnsiChar;const Key:TBMKey):PAnsiChar;
var
  i,pos,ls:Integer;
begin
if s=nil then
  Result:=nil
else if Key.ps=nil then
  Result:=s
else
  begin
  ls:=StrLen(s);
  Result:=nil;
  pos:=1;
  while pos<=ls-Key.Length do
    begin
    I:=pos-1;
    while I-pos+1<Key.Length do
      begin
      if s[I]<>Key.ps[I-pos+1] then
        Break;
      Inc(I);
      end;
    if i-pos+1=Key.Length then
      begin
      Result:=s+pos-1;
      Break;
      end
    else
      Inc(pos,Key.Offsets[Ord(s[pos+Key.Length-1])]+1);
    end;
  end;
end;

用法:

var
    AKey:TBMKey;
...
begin
AKey.ps:=要查找的子字符串
InitKeyDistance(AKey);
SundayStrStrA(要查找的字符串,AKey);
...
end;

 

分享到: