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,846 questions

51,767 answers

573 users

How to find the longest repeating substring in a string with Pascal

1 Answer

0 votes
program LongestRepeatingSubstring;

type
  TString = string;
  
// Function to return the minimum of two integers
function Min(a, b: Integer): Integer;
begin
  if a < b then
    Min := a
  else
    Min := b;
end;


// Function to find the longest common prefix between two strings
function LongestCommonPrefix(sub1, sub2: TString): TString;
var
  i, minLen: Integer;
begin
  minLen := Min(Length(sub1), Length(sub2));
  for i := 1 to minLen do
    if sub1[i] <> sub2[i] then
    begin
      LongestCommonPrefix := Copy(sub1, 1, i - 1);
      Exit;
    end;
  LongestCommonPrefix := Copy(sub1, 1, minLen);
end;

// Function to find the longest repeating substring
function LongestRepeatingSubstring(s: TString): TString;
var
  i, j, size: Integer;
  lrs, lcp: TString;
begin
  size := Length(s);
  lrs := '';

  for i := 1 to size do
    for j := i + 1 to size do
    begin
      lcp := LongestCommonPrefix(Copy(s, i, size - i + 1), Copy(s, j, size - j + 1));
      if Length(lcp) > Length(lrs) then
        lrs := lcp;
    end;

  LongestRepeatingSubstring := lrs;
end;

var
  s, result: TString;

begin
  s := 'javascriptpythonphpjavacdartcppjavacsharppascal';
  
  result := LongestRepeatingSubstring(s);
  
  WriteLn(result);
end.



(*
run:

pjavac

*)

 



answered Sep 22, 2025 by avibootz
...