program ABCWordCheck;
{$mode objfpc}{$H+}{$J-}
uses
SysUtils; { For LowerCase }
{
Purpose:
Determine whether a word is an "ABC word", meaning the letters
'a', 'b', and 'c' appear in alphabetical order somewhere in the word.
They do NOT need to be consecutive — only in the correct order.
Approach (efficient O(n)):
- Convert the entire word to lowercase once.
- Scan the lowercase word.
- Track whether 'a' has been seen, then 'b', then 'c'.
- If 'b' appears before 'a', or 'c' appears before 'b', the order is invalid.
- If we eventually see 'c' after both 'a' and 'b', the word is an ABC word.
}
function IsABCWord(const word: string): boolean;
var
i: integer;
c: char;
seenA, seenB: boolean;
lowerWord: string;
begin
seenA := False;
seenB := False;
{ Convert the whole word to lowercase once, efficiently }
lowerWord := LowerCase(word);
for i := 1 to Length(lowerWord) do
begin
c := lowerWord[i]; { Now c is already lowercase }
if c = 'a' then
seenA := True
else if c = 'b' then
begin
if not seenA then
begin
IsABCWord := False; { 'b' before 'a' → invalid }
Exit;
end;
seenB := True;
end
else if c = 'c' then
begin
if not seenB then
begin
IsABCWord := False; { 'c' before 'b' → invalid }
Exit;
end;
IsABCWord := True; { Found a → b → c in order }
Exit;
end;
end;
IsABCWord := False; { Did not find all three in order }
end;
var
word: string;
begin
word := 'algebraic';
WriteLn('Word: ', word);
if IsABCWord(word) then
WriteLn('Result: This IS an ABC word.')
else
WriteLn('Result: This is NOT an ABC word.');
end.
{
run:
Word: algebraic
Result: This IS an ABC word.
}