我的方法:很常规,设一个count记录大写字母的个数,如果是0,则true;如果是1,则返回第一个字符是否是true;如果等于总字符数,返回true,其他情况都是false。
class Solution {
public:
bool detectCapitalUse(string word) {
int count = 0;
for(int i = 0; i < word.size(); ++i)
{
if(word[i] >= 'A' && word[i] <= 'Z')
{
count++;
}
}
if(count == 0)
return true;
if(count == 1)
return word[0] >= 'A' && word[0] <= 'Z';
if(count == word.size())
return true;
return false;
}
};
但是判断大写字母这里,我写的太啰嗦,其实有个isupper(s[i])函数更快更好用!
还看到一种我不会的写法:
class Solution {
public:
bool detectCapitalUse(string word) {
int capCnt = count_if(word.begin(), word.end(), [](char c){return c <= 'Z';});
return !capCnt || capCnt == word.size() || (capCnt == 1 && word[0] <= 'Z');
}
};
用到了count_if函数:
bool greater10(int value)
{
return value >10;
}
//...
result1 = count_if(v1.begin(), v1.end(), greater10);