我的code,就是阅读理解,但是比较完备,tolerant String可能不规范的情况。
public boolean detectCapitalUse(String word) {
if (word == null || word.length() <= 1) {
return true;
}
for (int i = 0; i < word.length(); i++) {
//首字母小写
if (isLowerCaseLetter(word.charAt(0))) {
if (!isLowerCaseLetter(word.charAt(i))) {
return false;
}
}
//首字母大写
else if (isUpperCaseLetter(word.charAt(0))) {
if (isUpperCaseLetter(word.charAt(1))) {
if (i > 1 && !isUpperCaseLetter(word.charAt(i))) {
return false;
}
} else if (isLowerCaseLetter(word.charAt(1))) {
if (i > 1 && !isLowerCaseLetter(word.charAt(i))) {
return false;
}
}
} else {
return false;
}
}
return true;
}
private boolean isLowerCaseLetter(char c) {
return c <= 'z' && c >= 'a';
}
private boolean isUpperCaseLetter(char c) {
return c <= 'Z' && c >= 'A';
}
简洁的代码:
public class Solution {
public boolean detectCapitalUse(String word) {
int cnt = 0;
for(char c: word.toCharArray()) if('Z' - c >= 0) cnt++;
return ((cnt==0 || cnt==word.length()) || (cnt==1 && 'Z' - word.charAt(0)>=0));
}
}