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.
1public class Solution {
2 public bool DetectCapitalUse(string word) {
3 int capitalCount = 0;
4 foreach (char c in word) {
5 if (char.IsUpper(c)) {
6 capitalCount++;
7 }
8 }
9 return capitalCount == word.Length || capitalCount == 0 || (capitalCount == 1 && char.IsUpper(word[0]));
10 }
11}
In this C# implementation, we use foreach to iterate over the string and count capitals. We then verify if the capital letters count equals the string's length, equals zero, or is one with the first letter capitalized. True is returned for successful checks; 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.
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.