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.
1class Solution {
2 public boolean detectCapitalUse(String word) {
3 int capCount = 0;
4 for (char c : word.toCharArray()) {
5 if (Character.isUpperCase(c)) {
6 capCount++;
7 }
8 }
9 return capCount == word.length() || capCount == 0 || (capCount == 1 && Character.isUpperCase(word.charAt(0)));
10 }
11}
This Java solution counts the number of uppercase letters using a loop. Then, it checks if all letters are uppercase, none are uppercase, or the first one is uppercase and the rest are lowercase. We return true in any of these cases; false otherwise.
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.
1var detectCapitalUse = function(word
In JavaScript, this solution uses the test
method to check the word against a regex for correct capitalization. The regex matches all-uppercase, all-lowercase, or proper capitalized spelling (first uppercase, others lowercase).