C Solution


  • 1
    J
    bool detectCapitalUse(char* word) {
        int count = 0, first = 0;
        
        for (int i = 0; i < strlen(word); i++) {
            if (i == 0 && isupper(word[i])) {
                first = 1;
                count++;
            }
            else if (isupper(word[i])) {
                count++;
            }
        }
    
        if (count == strlen(word) || count == 0) return true;
        else if (first == 1 && count == 1) return true;
        else return false;
    }
    

  • 0

    Faster than using isupper().

    bool detectCapitalUse(char* word) {
        const int len = strlen(word);
        if (len > 1) {
            bool isUpper = 'A' <= word[1] && word[1] <= 'Z' && 'A' <= word[0] && word[0] <= 'Z';
            for (int i = 1; i < len; i ++) {
                if (isUpper && 'A' <= word[i] && word[i] <= 'Z' || !isUpper && 'a' <= word[i] && word[i] <= 'z') continue;
                return false;
            }
        }
        return true;
    }
    

Log in to reply
 

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