题目:
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.
分析:class Solution {
public boolean detectCapitalUse(String word) {
//判断给定的字符串是否是满足大写规则(即:1.全部为大写 2.全部为小写 3.只有首字母大写)
//思路:判断大写字母个数和字符串长度的,如果不相等,(一个的情况只需要判断首字母,否则false)
if(word.length()==0||word==null) return false;
int countAlpha=0;
for(char c:word.toCharArray()){
if(c>=65&& c<=90){
countAlpha++;
}
}
if(countAlpha!=word.length()&&countAlpha!=0){
if(!(countAlpha==1&&(word.charAt(0)>=65&&word.charAt(0)<=90))){
return false;
}
}
return true;
}
}