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.
1#include <cctype>
2#include <string>
3
4bool detectCapitalUse(std::string word) {
5 int capitalCount = 0;
6 int n = word.length();
7 for (char ch : word) {
8 if (isupper(ch)) capitalCount++;
9 }
10 return capitalCount == n || capitalCount == 0 || (capitalCount == 1 && isupper(word[0]));
11}
This C++ solution similarly iterates through the string to count the number of uppercase letters. We check if either all characters are uppercase, all lowercase, or only the first character is uppercase. If any of these holds true, we return true; otherwise, we return 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 re
2
3
In this Python solution, we apply a regular expression to match words fully capitalized, fully lowercase, or starting with one capital followed by lowercase letters. The re.match
function verifies if the string fits any pattern. Return true if matched, false otherwise.