In this Leetcode Detect Capital problem solution We define the usage of capitals in a word to be right when one of the following cases holds:

All letters in this word are capitals, like "USA".

All letters in this word are not capitals, like "leetcode".

Only the first letter in this word is capital, like "Google".

Given a string word, return true if the usage of capitals in it is right.

Leetcode Detect Capital problem solution


Problem solution in Python.

def detectCapitalUse(self, word: str) -> bool:
    b = [c.isupper() for c in word]
    return all(b) or not any(b) or (b[0] and not any(b[1:]))

Problem solution in Java.

class Solution {
    
    public boolean isCapital(char c){
        return c >= 65 && c <= 90;
    }
    
    public boolean detectCapitalUse(String word) {
        int len = word.length();
        int capCount = 0;
        
        for(char c : word.toCharArray()){
            if(isCapital(c))
                capCount++;
        }
        
        boolean allCap = len == capCount;
        boolean firstCap = capCount == 1 && isCapital(word.charAt(0));
        boolean noCap = capCount == 0;
        
        return allCap || firstCap || noCap;
    }
}


Problem solution in C++.

class Solution {
public:
    bool detectCapitalUse(string word) {
        if(word.size() == 1) {return true;}
        bool firstC = isupper(word[0]);
        bool allC = isupper(word[1]);
        if(!firstC && allC) {return false;}
        for(uint32_t i = 2; i < word.size(); i++) {
            if((isupper(word[i]) && !allC) || (islower(word[i]) && allC)) {
                return false;
            }
        }
        return true;
    }
};


Problem solution in C.

bool detectCapitalUse(char * word){
    if(strlen(word) == 1)return true;
    int i, small = 0, big = 0;
    for(i=0; word[i]; i++){
        if(word[i]>='a' && word[i] <='z')small++;
        if(word[i]>='A' && word[i] <='Z')big++;
    }
    if(small == 0 && big != 0)return true;
    else if(big == 0 && small != 0)return true;
    else if(big == 1 && word[0]>='A' && word[0] <='Z')return true;
    else return false;
}