Simple C++ with Explanation


  • 0
    T

    You have 3 possibilities :

    1. word is all lowercase -> return true
    2. word is all uppercase -> return true
    3. First letter is upper the rest is lower case -> return true

    Use a counter to keep track of capital letters. If counter == word.length then all are caps therefore true. If word[0] is capital and counter == 1 then return true as only the first letter is capital. If counter is 0 all words are lower case therefore return true. All other cases would equate to false.

    bool detectCapitalUse(string word)
    {
        int counter = 0;
        
        for (char c : word) {
            if (isupper(c)) {
                counter++;
            }
        }
        return counter == 0? true : ((counter == word.length()) || (isupper(word[0]) && counter == 1))? true : false;
    }
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.