题目:
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, like “Google”.
Otherwise, we define that this word doesn’t use capitals in a right way.
思路:
分三种情况,如果长度是1就是对的
如果都是小写就是对的
如果第二个之后都是小写就是对的,不用管第一个是不是大写
Code:
public boolean detectCapitalUse(String word) {
if (word.length() < 2)
return true;
// 如果全是大写字母
if (word.toUpperCase().equals(word))
return true;
// 如果第一个字母之后全是小写(第一个字母大小写无所谓)
if (word.substring(1).toLowerCase().
equals(word.substring(1)))
return true;
return false;
}