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.
题目大意:给定一个单词,检查大写字母的使用是否正确。我们定义满足以下三种形式即为正确使用大写字母:
1.所有的字母都是大写,例如“USA”
2.所有的字母都是小写,例如“leetcode”
3.只有首字母是大写(如果这个单词不止有一个字母的话),例如“Google”
注意:输入的单词非空。
如果输入的单词满足上述三个规则,那么返回True,否则返回False。
解题思路:把上面的三条规则读懂后发现,可以把情况分为两大类,一种情况是首字母小写,这时可以判断后面的所有字母是不是全为小写,如果是,返回True,否则,返回False;另一种是首字母大写(如果单词不止一个字母的话,可以再接着分,如果第二个字母也是小写,那么后面所有的字符都得是小写,反之,后面的字符都得是大写)。
这里我设置了一个标志位flag=0,如果出现不符合定义中的规则的情况,让flag变为1,经过循环之后只需要判断flag是否为1即可。
不过代码不够简洁优雅==AC后结果为68.98%
/**
* 第一种情况,如果第一个字母是小写,检查后面的所有字母是不是全为小写
* 第二种情况是如果第一个字母是大写,那检查后面是不是所有的字母都是大写或都是小写
*
*/
int len = word.length();
int flag = 0;
if(len==1){return true;}
//如果首字母小写,判断后面的字母有没有不是小写的
if(word.charAt(0)>='a'&&word.charAt(0)<='z'){
for(int i=1;i<len;i++){
if(word.charAt(i)<'a'||word.charAt(i)>'z'){
flag = 1;
}
}
if(flag==1){return false;}
}
//如果首字母大写,第二个字母也是大写,判断后面有没有不是大写的
else if(word.charAt(0)>='A'&&word.charAt(0)<='Z'&&word.charAt(1)>='A'&&word.charAt(1)<='Z'){
for(int i=2;i<len;i++){
if(word.charAt(i)<'A'||word.charAt(i)>'Z'){
flag = 1;
}
}
if(flag==1){return false;}
}
//如果首字母大写,第二个字母小写,判断后面有没有不是小写的
else if(word.charAt(0)>='A'&&word.charAt(0)<='Z'&&word.charAt(1)>='a'&&word.charAt(1)<='z'){
for(int i=2;i<len;i++){
if(word.charAt(i)<'a'||word.charAt(i)>'z'){
flag = 1;
}
}
if(flag==1){return false;}
}
return true;
然后看了一种3行搞定的,只需要统计大写字母的个数,确实很赞,不过效率为42.22%:
int count=0;
for(char c:word.toCharArray()){
if('Z'-c>=0) count++;
}
return (count==0||count==word.length()||('Z'-word.charAt(0)>=0&&count==1));