Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to find the longest substring without repeating characters in Pascal

1 Answer

0 votes
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

*)

 



answered Apr 7, 2025 by avibootz
...