How to resolve the algorithm Longest common substring step by step in the Delphi programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Longest common substring step by step in the Delphi programming language

Table of Contents

Problem Statement

Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string.   This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the longest common subsequence between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common substring is just "test".

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Longest common substring step by step in the Delphi programming language

Source code in the delphi programming language

program Longest_Common_Substring;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

function lcs(x, y: string): string;
var
  n, m, Alength: Integer;
  t, common: string;
  j: Integer;
  k: Integer;
begin

  Result := '';
  Alength := x.Length;

  for j := 0 to Alength - 1 do
    for k := Alength - j downto 0 do
    begin
      common := x.Substring(j, k);
      if (y.IndexOf(common) > -1) and (common.Length > Result.Length) then
        Result := common;
    end;
end;

var
  a, b: string;

begin
  a := 'thisisatest';
  b := 'testing123testing';
  if ParamCount = 2 then
  begin
    if not ParamStr(1).IsEmpty then
      a := ParamStr(1);
    if not ParamStr(2).IsEmpty then
      b := ParamStr(2);
  end;

  Writeln('string A = ', a);
  Writeln('string B = ', b);
  Writeln('LCsubstr = ', lcs(a, b));
  readln;
end.


  

You may also check:How to resolve the algorithm Towers of Hanoi step by step in the NetRexx programming language
You may also check:How to resolve the algorithm Sum of a series step by step in the Julia programming language
You may also check:How to resolve the algorithm Array concatenation step by step in the Quackery programming language
You may also check:How to resolve the algorithm Count in factors step by step in the Pascal programming language
You may also check:How to resolve the algorithm Binary strings step by step in the Common Lisp programming language