[leetcode]520. Detect Capital

[leetcode]520. Detect Capital


Analysis

Men are not good if they are not bad—— [ummmm~]

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.
这题主要是字母大小写的问题。

Implement

方法一
第一种情况,如果第一个字符是小写的,那么后面所有的字符都必须要是小写的;
第二种情况,如果第一个字符是大写的,那么要么后面所有的字符都是小写的,要么后面所有的字符都是大写的。

class Solution {
public:
    bool detectCapitalUse(string word) {
        int len = word.length();
        if(islower(word[0])){
            for(int i=1; i<len; i++){
                if(isupper(word[i]))
                    return false;
            }
            return true;
        }
        else if(isupper(word[0])){
            bool hasupper = false;
            bool haslower = false;
            for(int i=1; i<len; i++){
                if(isupper(word[i]))
                    hasupper = true;
                if(islower(word[i]))
                    haslower = true;
            }
            if(hasupper && haslower)
                return false;
            return true;
        }
    }
};

方法二
把字符串全部转换成大写得到字符串up,然后把字符串全部转换成小写low,如果原字符串和up相等或者跟low相等,则合法;当原字符串第一个字符大写时,如果后面所有的字符都是大写或者都是小写时,合法。

class Solution {
public:
    bool detectCapitalUse(string word) {
        int len = word.length();
        string up = "";
        string low = "";
        for(auto c:word)
            up += toupper(c);
        for(auto c:word)
            low += tolower(c);
        if(word == up || word == low)
            return true;
        if(isupper(word[0])){
            string t = word.substr(1, len-1);
            string t1 = up.substr(1, len-1);
            string t2 = low.substr(1, len-1);
            if(t == t1 || t == t2)
                return true;
        }
        return false;
    }
};

方法三
利用正则表达式进行判断

class Solution {
public:
    bool detectCapitalUse(string word) {
        return regex_match(word, regex("[A-Z]+|[a-z]+|[A-Z][a-z]*"));
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值