String:520. Detect Capital

    我的方法:很常规,设一个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);  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值