520. Detect Capital
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".
Otherwise, we define that this word doesn't use capitals in a right way.
1,如果全是小写字母,那么是有效的
2,如果全是大写字母,那么是有效的
3,如果第一个字母大写,后面的字母全是小写(如果有),那么也是有效的。
其余情况都是无效的
我的AC,简单直观
第一种:
public boolean detectCapitalUse2(String word) {
// 注意长度<=1
if (word == null || word.length() <= 1)
return true;
char fir = word.charAt(0);
char sec = word.charAt(1);
boolean f = Character.isUpperCase(fir);
boolean s = Character.isUpperCase(sec);
// 第一个字母小写,第二个字母大写
if (!f && s)
return false;
// 第一个字母大写,第二个字母大写
if (f && s) {
for (int i = 2; i < word.length(); i++)
// 如果之后出现小写,返回false(前两个字母大写)
if (Character.isLowerCase(word.charAt(i)))
return false;
}
// 如果第二个字母小写
else if (!s) {
for (int i = 2; i < word.length(); i++)
// 如果之后出现大写,返回false(第二个字母小写)
if (Character.isUpperCase(word.charAt(i)))
return false;
}
return true;
}
第二种:使用substring
public boolean detectCapitalUse(String word) {
// 长度小于2,返回true
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;
}
第三种来源于discuss(代理解)
public boolean detectCapitalUse(String word) {
if (word == null || word.length() == 0)
return true;
boolean first = false;
boolean all = false;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (c >= 'A' && c <= 'Z') {
if (i == 0) {
first = true;
all = true;
} else {
if (!all)
return false;
}
} else {
if (all && i > 1)
return false;
all = false;
}
}
return true;
}