We define the usage of capitals in a word to be right when one of the following cases holds:
"USA"."leetcode"."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
Constraints:
1 <= word.length <= 100word consists of lowercase and uppercase English letters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach to this problem involves checking every possible capitalization pattern of a word. We will consider all upper and lowercase variations to determine if the word adheres to the defined capital usage rules. Essentially, we check every single possibility.
Here's how the algorithm would work step-by-step:
def detect_capital_use(word):
# Check if all letters are uppercase
if word.isupper():
return True
# Check if all letters are lowercase
if word.islower():
return True
# Check if only the first letter is uppercase
if len(word) > 0 and word[0].isupper():
# Iterate through the remaining letters to ensure they are lowercase
for index in range(1, len(word)):
if word[index].isupper():
return False
return True
return FalseThe most efficient approach is to check the input word against a small number of possible valid capitalizations. We can decide if the word is valid very quickly this way. The problem constraints allow us to check only 3 conditions.
Here's how the algorithm would work step-by-step:
def detect_capital_use(word):
word_length = len(word)
#Check if all letters are uppercase
if word.isupper():
return True
#Check if all letters are lowercase
if word.islower():
return True
#Check if only the first letter is uppercase
if word_length > 0 and word[0].isupper():
# Need to check the rest of the word is lowercase
if word[1:].islower():
return True
return False| Case | How to Handle |
|---|---|
| Null or empty string | Return True immediately since an empty string technically satisfies the condition (vacuously true). |
| String with a single character | Return True as a single character string is considered to be all uppercase or all lowercase. |
| String with mixed case in the middle of the word | Return False, as this doesn't follow any capitalization rule. |
| String with numbers or special characters | Ignore non-alphabetic characters when checking case, only looking at the alphabetic characters within the string. |
| Very long string (potential performance issue) | The solution should iterate through the string once, so performance is O(n) and scales linearly with the string length. |
| String with all lowercase letters | Return True as this meets the condition of all lowercase. |
| String with all uppercase letters | Return True as this meets the condition of all uppercase. |
| String with only the first letter capitalized | Return True because the input matches the first letter capitalized format. |