Detect Capital
Problem
Return true if the usage of capitals in word is right: all letters uppercase (USA), all lowercase (leetcode), or only the first letter capital (Google).
word = "USA"truedef detect_capital_use(word):
return word.isupper() or word.islower() or word.istitle()
function detectCapitalUse(word) {
if (word === word.toUpperCase()) return true;
if (word === word.toLowerCase()) return true;
return word[0] === word[0].toUpperCase() &&
word.slice(1) === word.slice(1).toLowerCase();
}
class Solution {
public boolean detectCapitalUse(String word) {
return word.equals(word.toUpperCase())
|| word.equals(word.toLowerCase())
|| (Character.isUpperCase(word.charAt(0))
&& word.substring(1).equals(word.substring(1).toLowerCase()));
}
}
bool detectCapitalUse(string word) {
int upper = 0;
for (char c : word) if (isupper(c)) upper++;
return upper == (int)word.size() || upper == 0
|| (upper == 1 && isupper(word[0]));
}
Explanation
A word uses capitals correctly in exactly three cases: it is all uppercase (USA), all lowercase (leetcode), or only the first letter is capital (Google). The Python solution checks all three with one tidy line.
It uses built-in helpers: word.isupper() is true when every letter is uppercase, word.islower() is true when every letter is lowercase, and word.istitle() is true when the word starts with a capital and the rest are lowercase. If any of these is true, the usage is valid.
This works because those three patterns are the complete list of allowed forms, and each helper recognizes exactly one of them.
Example: word = "USA". Here isupper() returns true right away, so the whole expression is true. For "Google", istitle() is the one that returns true. For "gOOGLE", all three are false, so the answer is false.
Each check looks at every letter once, so the cost grows linearly with the word length.