LeetCode520—Detect Capital

本文介绍了一种用于检查字符串中大小写使用是否符合规范的算法。该算法能够判断一个单词是否正确地使用了大写字母,具体包括全小写、首字母大写或全大写这三种情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题

原题链接
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

分析

判断大小写又没有用错正确的用法分为三种情况:
1.全小写
2.首字母大写
3.全大写

我的思路是判断首字母大小写的情况,如果是小写,则后面再出现一个大写就return false
如果首字母是大写,则count一下后面大写的个数,后面大写的个数如果是0则是首字母大写的情况,如果是word.size()-1则表示全大写的情况。

 代码

bool islower(const char& c)
{
    if(c<='z'&&c>='a')
        return true;
    else
        return false;
}
class Solution {
public:
    bool detectCapitalUse(string word) {
        if(islower(word[0]))
        {
            for(int i = 1;i<word.size();++i)
            {
                if(!islower(word[i]))
                    return false;
            }
        }
        else
        {
            int count = 1;
            for(int i = 1;i<word.size();++i)
            {
                if(!islower(word[i]))
                    ++count;
            }
            return ((count==1)||(count==word.size()))?true:false;
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值