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".
Example 1:
Input: "USA" Output: True
Example 2:
Input: "FlaG" Output: False
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
按首字母是否大写的情况来分,大写时对后续的看相邻的是否性质一样,小写的后面有大写就输出falsepublic class Solution {
public boolean detectCapitalUse(String word) {
char[] ca = word.toCharArray();
if(isCapital(ca[0])==true){
for(int i=2; i<ca.length; i++){
if(isCapital(ca[i])!=isCapital(ca[i-1]))
return false;
}
}else{
for(int i=1; i<ca.length; i++)
if(isCapital(ca[i])==true)
return false;
}
return true;
}
private boolean isCapital(char c){
return c>='A' && c<='Z';
}
}
正则更加简单。。。
public boolean detectCapitalUse(String word) {
return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+");
}