Java Regex LeetCode 520

題目是這樣的 給一個字串 以下三種狀況return true

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”.

我的寫法蠻醜 效能也普普 (可能被compiler摧殘過 所以這樣寫 = =) 而且題目奇是有說只有 大寫跟小寫兩種案例 (不會有奇怪字元)

public boolean detectCapitalUse(String word) {

int num = (int)word.charAt(0);
int Case = 0;
if(num >= 97 && 122 >= num) {
Case = 2;
}else if(num >= 65 && 90 >= num){
if(word.length() > 1)
num = (int)word.charAt(1);
else
return true;

if(num >= 97 && 122 >= num){
Case = 3;
}else{
Case = 1;
}
}else{
return false;
}

for(int i = 1 ; i < word.length() ; i++) {
num = (int)word.charAt(i);

switch(Case) {
case 1:
if( num < 65 || 90 < num ){
return false;
}
break;
case 2:
if(num < 97 && 122 > num) {
return false;
}
case 3:
if(num < 97 && 122 > num) {
return false;
}
break;
default:
return false;
}
}
return true;
}

Java Regx

return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+");

一行解決 可是效能是倒數15%的。

不錯的解 (漂亮) 效能非常高

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));

}

主要利用 Z 的 ASCII 其實是 90 而 小寫 a 是 97

順帶一題 大寫是 65~90 小寫是 97~122

Show your support

Clapping shows how much you appreciated Bear熊’s story.