我的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));
}
}