const
MAX_ANSWER_HASH = $FFF;
HashMapValue: array ['A'..'J'] of Byte = (1, 2, 3, 4, 5, 6, 7, 8, 9, $A);
type
TStringHashArray = array [0..MAX_ANSWER_HASH - 1] of Boolean;
function GetHashValue(C1, C2, C3: Char): Word;
begin
Result := (
((HashMapValue[C1] and $F) shl 8) +
((HashMapValue[C2] and $F) shl 4) +
((HashMapValue[C3] and $F))) and MAX_ANSWER_HASH;
end;
procedure SetStringHash(var HashArray: TStringHashArray; const S: string);
procedure SetHash(C1, C2, C3: Char); overload;
var
Hash: Word;
begin
Hash := GetHashValue(C1, C2, C3);
if not HashArray[Hash] then
HashArray[Hash] := True;
end;
var
C1, C2, C3, C4, C5: Char;
begin
C1 := S[1];
C2 := S[2];
C3 := S[3];
C4 := S[4];
C5 := S[5];
// 按顺序的情况下,只要有5种组合需要,如下:
SetHash(C1, C2, C3);
SetHash(C1, C3, C4);
SetHash(C1, C4, C5);
SetHash(C2, C3, C4);
SetHash(C2, C4, C5);
SetHash(C3, C4, C5);
end;
function GetStringHash(HashArray: TStringHashArray; const S: string): Boolean;
var
C1, C2, C3, C4, C5: Char;
begin
C1 := S[1];
C2 := S[2];
C3 := S[3];
C4 := S[4];
C5 := S[5];
// 只判断5种组合的Boolean值是否存在即可
Result :=
HashArray[GetHashValue(C1, C2, C3)] or
HashArray[GetHashValue(C1, C3, C4)] or
HashArray[GetHashValue(C1, C4, C5)] or
HashArray[GetHashValue(C2, C3, C4)] or
HashArray[GetHashValue(C2, C4, C5)] or
HashArray[GetHashValue(C3, C4, C5)];
end;
procedure GetExistsData(Exists: TStrings; Table1, Table2: TStrings); overload;
var
I: Integer;
HashArray: TStringHashArray;
begin
FillChar(HashArray, SizeOf(HashArray), 0);
Exists.Clear;
for I := 0 to Table2.Count - 1 do
SetStringHash(HashArray, Table2);
for I := 0 to Table1.Count - 1 do
begin
if GetStringHash(HashArray, Table1) then
Exists.Add(Table1);
end;
end;
type
TStringArray = array of string;
procedure GetExistsData(var Exists: TStringArray; Table1, Table2: TStringArray); overload;
var
I, Index, Count: Integer;
HashArray: TStringHashArray;
begin
FillChar(HashArray, SizeOf(HashArray), 0);
for I := 0 to Length(Table2) - 1 do
SetStringHash(HashArray, Table2);
Index := 0;
Count := Length(Table1);
SetLength(Exists, Count);
for I := 0 to Count - 1 do
begin
if GetStringHash(HashArray, Table1) then
begin
Exists[Index] := Table1;
Inc(Index);
end;
end;
SetLength(Exists, Index);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
GetExistsData(Memo3.Lines, Memo1.Lines, Memo2.Lines);
end;