Problem description:

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:

  1. All letters in this word are capitals, like “USA”.
  2. All letters in this word are not capitals, like “leetcode”.
  3. Only the first letter in this word is capital, like “Google”.
    Otherwise, we define that this word doesn’t use capitals in a right way.

Example 1:

1
2
Input: "USA"
Output: True

Example 2:

1
2
Input: "FlaG"
Output: False

Solution:

The question mentioned given a word, so during the interview, we should starting from clarifying the input.

  • Does the word contains numbers or symbols?

In the description, there’re three conditions to return True. So we could count the number of capital characters to verify.

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def detectCapitalUse(self, word: str) -> bool:
# Only first word be capital || All words are capital || no capital
# number of capital words
num_Cap, n = 0, len(word)
for x in word:
num_Cap += x.isupper()
if num_Cap == n or num_Cap == 1 and word[0].isupper() or num_Cap == 0:
return True
else:
return False

Another thought is to check the condition of 1~n. That is to say, character 1~n should be all lower case or upper case. But an exception is the first character word[0] is lower case but word[1~n] is upper case.
Another thought is to check the condition of 1~n. We should only return True if the whole string is lower/upper case, or only first character is upper case and word[1:] is lower case.

1
2
3
4
5
6
7
8
9
class Solution:
def detectCapitalUse(self, word: str) -> bool:

if word.lower() == word or word.upper() == word:
return True
elif word[0].isupper() and word[1:].lower() == word[1:]:
return True
else:
return False

time complexity: $O(n)$
space complexity: $O(n)$

reference:
related problem: