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
...