We define the usage of capitals in a word to be right when one of the following cases holds:
"USA"."leetcode"."Google".Given a string word, return true if the usage of capitals in it is right.
Example 1:
Input: word = "USA" Output: true
Example 2:
Input: word = "FlaG" Output: false
Constraints:
1 <= word.length <= 100word consists of lowercase and uppercase English letters.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.
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.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the word.
Space Complexity: O(1), as we only use a few variables.
Using regular expressions, we can check for proper capitalization by defining patterns that match accepted formats: all uppercase, all lowercase, or initial capital only.
In this Python solution, we apply a regular expression to match words fully capitalized, fully lowercase, or starting with one capital followed by lowercase letters. The re.match function verifies if the string fits any pattern. Return true if matched, false otherwise.
Java
JavaScript
C#
Time Complexity: O(n), considering regex must check each letter.
Space Complexity: O(1), since regex requires negligible extra space.
| Approach | Complexity |
|---|---|
| Check All Conditions Manually | Time Complexity: O(n), where n is the length of the word. |
| Regular Expression Matching | Time Complexity: O(n), considering regex must check each letter. |
Detect Capital - LeetCode Interview Coding Challenge [Java Brains] • Java Brains • 27,391 views views
Watch 9 more video solutions →Practice Detect Capital with our built-in code editor and test cases.
Practice on FleetCode