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,656 questions

55,396 answers

573 users

How to check whether a word is an ABC word in Java

1 Answer

0 votes
public class ABCWordCheck {

    /**
        Function: isABCWord
        Purpose:
            Check whether the letters 'a', 'b', and 'c' appear in the word
            in alphabetical order (a → b → c). They do NOT need to be consecutive.

        Efficient Algorithm (O(n)):
            - Convert the word to lowercase once.
            - Scan characters from left to right.
            - Track whether 'a' has appeared, 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', return true.

        Notes:
            - Case-insensitive.
            - Uses only built-in Java methods.
    */
    public static boolean isABCWord(String word) {
        String lower = word.toLowerCase();

        boolean seenA = false;
        boolean seenB = false;

        for (int i = 0; i < lower.length(); i++) {
            char c = lower.charAt(i);

            if (c == 'a') {
                seenA = true;
            } else if (c == 'b') {
                if (!seenA) return false;   // 'b' before 'a' → invalid
                seenB = true;
            } else if (c == 'c') {
                if (!seenB) return false;   // 'c' before 'b' → invalid
                return true;                // Found a → b → c in order
            }
        }

        return false;  // Did not find all three in order
    }

    public static void main(String[] args) {
        String word = "algebraic";  // Example word

        System.out.println("Word: " + word);

        if (isABCWord(word)) {
            System.out.println("Result: This IS an ABC word.");
        } else {
            System.out.println("Result: This is NOT an ABC word.");
        }
    }
}


/*
run:

Word: algebraic
Result: This IS an ABC word.

*/

 



answered Jul 10 by avibootz
...