program FirstRepeatedCharacterExample;
{$mode objfpc}{$H+} // Enable modern Object Pascal features (Result variable, Exit with value)
{**
* Finds the first character that repeats as you scan a string from left to right.
*
* @param S The input string to evaluate.
* @return The first repeated character, or #0 if no character repeats.
*}
function FindFirstRepeatedCharacter(const S: string): Char;
var
Seen: array[0..255] of Boolean;
I: Integer;
C: Char;
begin
{ Initialize the tracking array to False (all elements unvisited) }
FillChar(Seen, SizeOf(Seen), False);
{ Iterate through the 1-indexed Free Pascal string }
for I := 1 to Length(S) do
begin
C := S[I];
{ If this character's ASCII value was already marked, it's our first repeat }
if Seen[Byte(C)] then
Exit(C);
{ Mark this character as seen }
Seen[Byte(C)] := True;
end;
{ Return a null character if all characters in the string are unique }
Result := #0;
end;
{ --- Test Cases --- }
var
TestCases: array[0..3] of string;
TestStr: string;
ResultChar: Char;
begin
TestCases[0] := 'abca';
TestCases[1] := 'abcbd';
TestCases[2] := 'abcde';
TestCases[3] := 'abcdxypcbop';
for TestStr in TestCases do
begin
ResultChar := FindFirstRepeatedCharacter(TestStr);
if ResultChar <> #0 then
Writeln('Input: "', TestStr, '" -> First Repeated: ', ResultChar)
else
Writeln('Input: "', TestStr, '" -> No repeated characters');
end;
end.
(*
run:
Input: "abca" -> First Repeated: a
Input: "abcbd" -> First Repeated: b
Input: "abcde" -> No repeated characters
Input: "abcdxypcbop" -> First Repeated: c
*)