LeetCode 检测大写字母
给定一个单词,你需要判断单词的大写使用是否正确。
我们定义,在以下情况时,单词的大写用法是正确的:
全部字母都是大写,比如"USA"。
单词中所有字母都不是大写,比如"leetcode"。
如果单词不只含有一个字母,只有首字母大写, 比如 "Google"。
否则,我们定义这个单词没有正确使用大写字母。
示例 1:
输入: "USA"
输出: True
示例 2:
输入: "FlaG"
输出: False
注意: 输入是由大写和小写拉丁字母组成的非空单词。
思路分析: 分成四种情况,分别对号入座即可。
//第一种情况:单词只有一个字母
//第二种情况:所有字母都是小写
//第三种情况:第一个字母大写,第二个小写,检测后面的字母是否都是小写
//第四种情况:前两个字母都是大写,检测剩余的字母是否都是大写
class Solution {
public:
bool detectCapitalUse(string word) {
int wordSize = word.size();
if (wordSize == 1){
//第一种情况:单词只有一个字母
return true;
}
else if (word[0] >= 'a' && word[0] <= 'z'){
//第二种情况:所有字母都是小写
for (int index = 1; index < wordSize; ++index){
if (word[index] < 'a' || word[index] > 'z'){//检测是否是小写
return false;
}
}
return true;
}
else if (word[1] >= 'a' && word[1] <= 'z'){
//第三种情况:第一个字母大写,第二个小写,检测后面的字母是否都是小写
for (int index = 2; index < wordSize; ++index){
if (word[index] < 'a' || word[index] > 'z'){
return false;
}
}
return true;
}
else{
//第四种情况:前两个字母都是大写,检测剩余的字母是否都是大写
for (int index = 2; index < wordSize; ++index){
if (word[index] > 'Z' || word[index] < 'A'){
return false;
}
}
return true;
}
}
};