This problem is from Leetcode – Detect Capital. Problem statement in short is as below:
Return true if a word is all uppercase, all lowercase, or only the first letter is uppercase; otherwise, false.
Solution
To determine if the usage of capitals in a given word is correct according to the specified rules, we can implement a function that checks the following conditions:
- All letters are uppercase.
- All letters are lowercase.
- Only the first letter is uppercase, and the rest are lowercase.
See the code sample below:
public boolean detectCapitalUse(String word) {
Boolean isCapital = false;
// check if all chars are lowercase
if(word.equals(word.toLowerCase())) {
return true;
}
// check if all chars are uppercase
else if(word.equals(word.toUpperCase())) {
return true;
}
// check if first char is uppercase and rest are lowercase
if(Character.isUpperCase(word.charAt(0))) {
String str = word.substring(1, word.length());
if(str.equals(str.toLowerCase())) {
return true;
}
}
return isCapital;
}
You can checkout the code from Github here: Detect Capital – First Approach. See the performance of this approach below:
PERFORMANCE ANALYSIS
RUNTIME | 2 ms | Beats 38.90 % |
MEMORY | 41.28 MB | Beats 99.07 % |
TIME COMPLEXITY | O (N) |