Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to check whether a word is an ABC word in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <cctype>

/*
    Function: isABCWord
    Purpose:  Check whether the letters 'a', 'b', and 'c' appear in the word
              in alphabetical order (a → b → c), not necessarily consecutively.

    Algorithm (efficient O(n)):
      - Scan the word once.
      - Track which of the letters we have already seen.
      - We expect them in order: first 'a', then 'b', then 'c'.
      - If we see 'b' before 'a', or 'c' before 'b', the word is NOT an ABC word.
      - If we see all three in correct order, return true.

    Notes:
      - Case-insensitive: 'A', 'B', 'C' also count.
      - Other letters are ignored.
*/
bool isABCWord(const std::string& word) {
    bool seenA = false;
    bool seenB = false;

    for (char ch : word) {
        char c = std::tolower(static_cast<unsigned char>(ch));

        if (c == 'a') {
            seenA = true;
        }
        else if (c == 'b') {
            // If 'b' appears before 'a', order is broken
            if (!seenA) return false;
            seenB = true;
        }
        else if (c == 'c') {
            // If 'c' appears before 'b', order is broken
            if (!seenB) return false;
            return true;  // We found a, then b, then c in order
        }
    }

    // If we finish scanning without seeing all three in order
    return false;
}

int main() {
    std::string word = "algebraic";

    if (isABCWord(word)) {
        std::cout << "This IS an ABC word.\n";
    } else {
        std::cout << "This is NOT an ABC word.\n";
    }
}


/*
run:

This IS an ABC word.

*/

 



answered Jul 10 by avibootz
...