We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "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.
My Solution
We can first check whether the string is all lower case or all upper case by converting to all lowercase and checking whether the word is unchanged or converting to all uppercase and checking whether the word is unchanged. If it is we return true. If not, then the first character must be uppercase. If we find that the first character is lowercase, we can return false. Finally, the rest of the word must be lowercase so we iterate through the String and if any character is uppercase, we return false. Otherwise we return true.
Time complexity is O(n) because we have to iterate the string a constant number of times to check the three conditions. Space complexity is also O(n) to store the intermediate all uppercase or all lowercase strings.
class Solution {
public boolean detectCapitalUse(String word) {
int n = word.length();
if (word.equals(word.toUpperCase()) || word.equals(word.toLowerCase())) {
return true;
}
if (Character.isLowerCase(word.charAt(0))) {
return false;
}
for (int i = 1; i < n; i++) {
if (Character.isUpperCase(word.charAt(i))) {
return false;
}
}
return true;
}
}