Given a word, you need to judge whether the usage of capitals in it is right or not.
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 if it has more than one letter, like "Google".
Example 1:
Input: "USA" Output: True
Example 2:
Input: "FlaG" Output: False
Note:The input will be a non-empty word consisting of uppercase and lowercase latin letters.
Subscribe to see which companies asked this question.
Solution:
Tips: easy
Java Regex will be better.
Java Code:
public class Solution {
public boolean detectCapitalUse(String word) {
if (null == word || word.isEmpty()) {
return true;
}
char firstCharacter = word.charAt(0);
if (firstCharacter >= 'A' && firstCharacter <= 'Z') {
String upper = word;
if (upper.toUpperCase().equals(word)) {
return true;
}
String wordCopy = word;
wordCopy = firstCharacter + wordCopy.toLowerCase().substring(1, wordCopy.length());
return wordCopy.equals(word);
} else {
String lower = word;
return lower.toLowerCase().equals(word);
}
}
}