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.
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.