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.
1var detectCapitalUse = function(word) {
2 let capitalCount = 0;
3 for (let ch of word) {
4 if (ch === ch.toUpperCase()) {
5 capitalCount++;
6 }
7 }
8 return capitalCount === word.length || capitalCount === 0 || (capitalCount === 1 && word[0] === word[0].toUpperCase());
9};
This JavaScript solution loops over the characters of the word, tallies uppercase letters, then checks if all, none, or just the first are uppercase. If so, it returns 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.
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).