题目地址:https://leetcode.com/problems/detect-capital/#/description
简单理解:
这道题目主要就是检测大写的使用是否正确,如果符合以下三个条件的视为正确:
1. All letters in this word are capitals, like "USA".
2. All letters in this word are not capitals, like "leetcode".
3. Only the first letter in this word is capital if it has more than one letter, like "Google".
总的来说就是全部大写,全部小写,只有第一个字母大写的单词就是正确的。
我的解法:通过检测小写字母的个数来进行判断,如果个数等于word的长度,说明全部是小写字母,符合;如果是0,说明全部是大写,符合;如果等于word的长度减1,就要检查首字母是否是大写,是的话则符合.
代码:
class Solution {
public:
bool detectCapitalUse(string word) {//大写使用检测
int len = word.length();
bool result = true;
int n = 0;
for(int i = 0;i<len;i++){
if(word[i]>='a' && word[i] <='z'){
result = false;
n++;
}
}
//如果全部是小写或者只有第一个是大写的话应该是true
if(n == len-1&&word[0]>='A'&&word[0]<='Z' || n == len) result = true;
return result;
}
};