How to check if two strings are isomorphic in Pascal

1 Answer

0 votes
// Two strings are isomorphic if characters in one can be replaced to get the other, 
// while preserving the order.

program IsomorphicStrings;

function AreIsomorphic(s, t: string): boolean;
var
  mapST, mapTS: array[0..255] of integer;
  i: integer;
  c1, c2: char;
begin
  if length(s) <> length(t) then
    exit(false);

  for i := 0 to 255 do
  begin
    mapST[i] := 0;
    mapTS[i] := 0;
  end;

  for i := 1 to length(s) do
  begin
    c1 := s[i];
    c2 := t[i];

    if mapST[ord(c1)] <> mapTS[ord(c2)] then
      exit(false);

    mapST[ord(c1)] := i;
    mapTS[ord(c2)] := i;
  end;

  AreIsomorphic := true;
end;

begin
  writeln(AreIsomorphic('egg', 'add'));    
  writeln(AreIsomorphic('foo', 'bar'));     
  writeln(AreIsomorphic('paper', 'title')); 
end.




(*
run:

TRUE
FALSE
TRUE

*)


 



answered Dec 19, 2025 by avibootz
edited Dec 19, 2025 by avibootz
...