clueless coding // TODO: be smarter

LeetCode 520. Detect Capital: C++ Solution



Problem Statement


Given a word, you need to judge whether the usage of capitals in it is right or not.

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 if it has more than one letter, like “Google”.

Otherwise, we define that this word doesn’t use capitals in a right way.

Function Signature (C++):
  bool detectCapitalUse(string word)

Inputs:
  s = "USA"

Outputs:
  true

Inputs:
  s = "FlaG"

Outputs:
  false



TL;DR Code Solution


bool detectCapitalUse(string word) {
    return countCaps(word) == word.length() || countCaps(word) == 0 || hasFirstCap(word);
}

int countCaps(string word) {
    int count = 0;
    for (int i = 0; i < word.length(); i++) {
        if (isCapital(word[i])) {
            count++;
        }
    }
    return count;
}

bool hasFirstCap(string word) {
    return word.length() > 1 &&
        isCapital(word[0]) &&
        countCaps(word) == 1;
}

bool isCapital(char character) {
    int charVal = (int)(character - 'A');
    if (charVal >= 0 && charVal < 26) {
        return true;
    }
    return false;
}