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.
1using System.Text.RegularExpressions;
2
3public class Solution {
4 public bool DetectCapitalUse(string word) {
return Regex.IsMatch(word, "^[A-Z]+$|^[a-z]+$|^[A-Z][a-z]*$");
}
}
This C# code uses the Regex.IsMatch
function to verify if the capitalization of a word matches specified regular expression patterns. It checks entire words for three valid capitalization styles.