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 <= 100
word
consists of lowercase and uppercase English letters.This problem asks us to determine if the capitalization of a given word is valid according to three rules:
The most efficient approach involves counting the number of uppercase letters and checking against the rules. This avoids multiple iterations through the string.
Count Uppercase Letters: Iterate through the input string word
and count the number of uppercase characters. We can use built-in functions like isupper()
(Python) or Character.isUpperCase()
(Java) to efficiently check the case of each character.
Check Conditions: Based on the count of uppercase letters:
Return Result: Return true
if any of the valid conditions are met, and false
otherwise.
word
. We iterate through the string once to count uppercase letters.class Solution:
def detectCapitalUse(self, word: str) -> bool:
uppercase_count = sum(1 for char in word if char.isupper())
return (uppercase_count == 0 or
uppercase_count == len(word) or
(uppercase_count == 1 and word[0].isupper()))
class Solution {
public boolean detectCapitalUse(String word) {
int uppercaseCount = 0;
for (char c : word.toCharArray()) {
if (Character.isUpperCase(c)) {
uppercaseCount++;
}
}
return (uppercaseCount == 0 ||
uppercaseCount == word.length() ||
(uppercaseCount == 1 && Character.isUpperCase(word.charAt(0))));
}
}
class Solution {
public:
bool detectCapitalUse(string word) {
int uppercaseCount = 0;
for (char c : word) {
if (isupper(c)) {
uppercaseCount++;
}
}
return (uppercaseCount == 0 ||
uppercaseCount == word.length() ||
(uppercaseCount == 1 && isupper(word[0])));
}
};
const detectCapitalUse = (word) => {
let uppercaseCount = 0;
for (let i = 0; i < word.length; i++) {
if (word[i] === word[i].toUpperCase()) {
uppercaseCount++;
}
}
return (uppercaseCount === 0 ||
uppercaseCount === word.length ||
(uppercaseCount === 1 && word[0] === word[0].toUpperCase()));
};
func detectCapitalUse(word string) bool {
uppercaseCount := 0
for _, char := range word {
if unicode.IsUpper(char) {
uppercaseCount++
}
}
return (uppercaseCount == 0 ||
uppercaseCount == len(word) ||
(uppercaseCount == 1 && unicode.IsUpper(rune(word[0]))))
}
These code examples all implement the same core algorithm, showcasing the solution's adaptability across programming languages. The choice of language primarily affects the syntax for string iteration and character case checking, but the underlying logic remains consistent.