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 <stdbool.h>
2#include <ctype.h>
3
4bool detectCapitalUse(char * word) {
5 int n = strlen(word);
6 int capitalCount = 0;
7 for (int i = 0; i < n; i++) {
8 if (isupper(word[i])) capitalCount++;
9 }
10 if (capitalCount == n) return true;
11 if (capitalCount == 0) return true;
12 if (capitalCount == 1 && isupper(word[0])) return true;
13 return false;
14}
In this C solution, we iterate through the given word and count the number of capital letters. We then check for three conditions:
We return true if any of these conditions are satisfied; 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 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.