520. Detect Capital

520. Detect Capital

An example of a string in C++

Nhut Nguyen's photo
Nhut Nguyen
·Dec 26, 2022·

2 min read

Problem statement

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.

Example 1

Input: word = "USA"
Output: true

Example 2

Input: word = "FlaG"
Output: false


  • 1 <= word.length <= 100,

  • word consists of lowercase and uppercase English letters.


Only when the first two characters of the word are uppercase, the rest must be the same. Otherwise, the rest is always lowercase.


#include <string>
#include <iostream>
using namespace std;
bool isValidCase(const char& c, const bool isLower) {
    if (isLower) {
        return 'a' <= c && c <= 'z';
    return 'A' <= c && c <= 'Z';
bool detectCapitalUse(string word) {
    if (word.length() == 1) {
        return true;
    bool isLower = true;
    if (isValidCase(word[0], false) && isValidCase(word[1], false)) {
        isLower = false;
    for (int i = 1; i < word.length(); i++) {
        if (!isValidCase(word[i], isLower)) {
            return false;
    return true;
int main() {
    cout << detectCapitalUse("USA") << endl;
    cout << detectCapitalUse("FlaG") << endl;
    cout << detectCapitalUse("leetcode") << endl;
    cout << detectCapitalUse("Google") << endl;


  • Runtime: O(N), where N = word.length.

  • Extra space: O(1).


Thanks for reading. Feel free to share your thought about my content and check out my FREE book “10 Classic Coding Challenges”.

Did you find this article valuable?

Support LeetSolve by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
Share this