Sponsored
Sponsored
This approach manually checks each of the three conditions for correct capitalization. You can iterate through the word to verify that it either matches all caps, all lowercase, or the first letter is the only capital letter.
Time Complexity: O(n), where n is the length of the word.
Space Complexity: O(1), as we only use a few variables.
1def detectCapitalUse(word: str) -> bool:
2 capital_count = sum(1 for c in word if c.isupper())
3 return (capital_count == len(word) or
4 capital_count == 0 or
5 (capital_count == 1 and word[0].isupper()))
In this Python solution, we use a generator expression to count uppercase letters. We then verify if all letters are uppercase, none, or only the first one is uppercase. If any condition is satisfied, we return true; otherwise, false.
Using regular expressions, we can check for proper capitalization by defining patterns that match accepted formats: all uppercase, all lowercase, or initial capital only.
Time Complexity: O(n), considering regex must check each letter.
Space Complexity: O(1), since regex requires negligible extra space.
1import java.util.regex.*
This Java solution utilizes the matches
method to see if the word complies with capitalization rules. The patterns used capture all uppercase, all lowercase, or an initial uppercase followed by lowercase letters.