How to find the last repeated character in a string with Pascal

1 Answer

0 votes
program LastRepeatedCharacter;

{$mode objfpc}{$H+}

uses
  SysUtils;

{
  Finds the last repeated character in a string.

  Examples:
    'abca'          -> 'a'
    'abcbd'         -> 'b'
    'abcde'         -> #0 (not found)
    'abcdxypcbop'   -> 'p'
    'abcdxypcbadom' -> 'd'

  Time Complexity: O(n)
  Space Complexity: O(1)
}
function FindLastRepeatedCharacter(const S: string): Char;
var
  Frequency: array[0..255] of Integer;
  I: Integer;
  Ch: Byte;
begin
  FillChar(Frequency, SizeOf(Frequency), 0);

  { Count character frequencies }
  for I := 1 to Length(S) do
  begin
    Ch := Ord(S[I]);
    Inc(Frequency[Ch]);
  end;

  { Scan from right to left }
  for I := Length(S) downto 1 do
  begin
    Ch := Ord(S[I]);

    if Frequency[Ch] > 1 then
    begin
      Result := S[I];
      Exit;
    end;
  end;

  { No repeated character found }
  Result := #0;
end;

var
  ResultChar: Char;
begin
  Writeln(FindLastRepeatedCharacter('abca'));         
  Writeln(FindLastRepeatedCharacter('abcbd'));        

  ResultChar := FindLastRepeatedCharacter('abcde');
  if ResultChar <> #0 then
    Writeln(ResultChar)
  else
    Writeln(' ');

  Writeln(FindLastRepeatedCharacter('abcdxypcbop'));   
  Writeln(FindLastRepeatedCharacter('abcdxypcbadom')); 
end.


(*
run:

a
b
 
p
d

*)

 



answered 5 days ago by avibootz
...