program LongestSubstring;
function LongestSubstring(s: String): String;
var
start, maxLength, endIdx, currentLength: Integer;
charIndex: array[' '..'~'] of Integer; // Character index map
longestSubstr: String;
ch: Char;
begin
// Initialize variables
start := 1; // Pascal strings are 1-indexed
maxLength := 0;
longestSubstr := '';
for ch := ' ' to '~' do
charIndex[ch] := 0; // Initialize the character index map to 0
// Iterate over the string
for endIdx := 1 to Length(s) do
begin
ch := s[endIdx];
// If the character is within the current window, update the start pointer
if (charIndex[ch] >= start) then
start := charIndex[ch] + 1;
// Update the character's latest index
charIndex[ch] := endIdx;
// Calculate the current substring length
currentLength := endIdx - start + 1;
if currentLength > maxLength then
begin
maxLength := currentLength;
longestSubstr := Copy(s, start, currentLength);
end;
end;
// Return the longest substring
LongestSubstring := longestSubstr;
end;
var
result: String;
begin
// Test cases
result := LongestSubstring('abcabcbb');
WriteLn(result); // Output: "abc"
result := LongestSubstring('bbbbb');
WriteLn(result); // Output: "b"
result := LongestSubstring('xwwwqfwwxqwyq');
WriteLn(result); // Output: "xqwy"
end.
(*
run:
abc
b
xqwy
*)