给定一个单词,你需要判断单词的大写使用是否正确。
我们定义,在以下情况时,单词的大写用法是正确的:
全部字母都是大写,比如"USA"。
单词中所有字母都不是大写,比如"leetcode"。
如果单词不只含有一个字母,只有首字母大写, 比如 "Google"。
否则,我们定义这个单词没有正确使用大写字母。
示例 1:
输入: "USA"
输出: True
示例 2:
输入: "FlaG"
输出: False
注意: 输入是由大写和小写拉丁字母组成的非空单词
=========================================================================
比较好理解的方法:我们可以计算给定字母中大写与小写字母的个数,如果:①全是小写字母-true②全是大写字母-true③首字母是大写,并且小写字母有(字母的长度 - 1)个,满足三个条件之一就是true。
代码:
public static void main(String[] args) {
String s1 = "leEtcode";
String s2 = "Goole";
String s3 = "DFdS";
System.out.println(detectCapitalUse(s1));
System.out.println(detectCapitalUse(s2));
System.out.println(detectCapitalUse(s3));
}
public static boolean detectCapitalUse(String word){
int l = 0,b = 0; //定义word中大写与小写字母的个数
for(int i = 0;i < word.length();i++){
if(word.charAt(i) >= 65 && word.charAt(i) <= 90){
b++; //遍历word,如果字母是大写b就加1
}else{
l++; //否则l就加1
}
}
/*
* ①全是小写字母-true
* ②全是大写字母-true
* ③首字母是大写,并且小写字母有(字母的长度 - 1)个.
* 满足三个条件之一就是true
*/
if((l == word.length()) ||
((l == word.length() - 1) && (word.charAt(0) >= 65 && word.charAt(0) <= 90)) ||
(b == word.length()))
return true;
else
return false;
}