520.Detect Capital
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”.
Otherwise, we define that this word doesn’t use capitals in a right way.
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.
翻译:给定一个字符串,判断是否为capitals,三类单词可以被判定为capitals单词,
例如:”USA”:全为大写字母;”leetcode”:全为小写字母;”Google”:首字母为大写字母,其余全为小写字母;
其余全不符合要求.提示:给出的都为非空且由大小写字母组成的字符串。
思路:通过查询ASCII表,大写字母范围:65-90,小写字母范围:97-122。遍历每个字母得到大写字母和小写字母的数量,其中一个数量为1,都为true;若大写字母数量为1,且第一个字符为大写字母,返回true。
public class DetectCapital {
public boolean detectCapitalUse(String word) {
Boolean result = true;
int bCount = 0;
int sCount = 0;
for (int i=0;i<word.length();i++){
if (word.charAt(i) > 64 && word.charAt(i) < 91){
bCount++;
}else if (word.charAt(i)>96 && word.charAt(i)<123){
sCount++;
}
if (bCount == 0 || sCount == 0){
result = true;
}else if (bCount == 1 && word.charAt(0)>64 && word.charAt(0)<91){
result = true;
}else {
result = false;
}
}
return result;
}
public static void main(String[] args) {
DetectCapital detectCapital = new DetectCapital();
System.out.println(detectCapital.detectCapitalUse("GOOGLE"));
}
}
显然,这肯定不是最优的解决方法,
public boolean detectCapitalUse(String word) {
return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+");
}
这种方法是通过matches方法,通过正则表达式匹配正确的字符串 [A-Z]+ 或 [a-z]+ 或 [A-Z][a-z]+