【LeetCode】520. 检测大写字母

版权声明:made by YYT https://blog.csdn.net/qq_37621506/article/details/83586264

1.题目

给定一个单词,你需要判断单词的大写使用是否正确。
我们定义,在以下情况时,单词的大写用法是正确的:
全部字母都是大写,比如"USA"。
单词中所有字母都不是大写,比如"leetcode"。
如果单词不只含有一个字母,只有首字母大写, 比如 “Google”。
否则,我们定义这个单词没有正确使用大写字母。

2.思路

考虑三种情况;
遍历字符串,记录小写字母的数量,和最后一个大写字母的下标;
如果小写字母数量=0,情况一;
如果小写字母数量=字符串长度,情况二;
此外,下标=0,情况三

3.代码

class Solution {
public:
    bool detectCapitalUse(string word) {
         int c=0,index;
    for(int i=0;i<word.length();i++){
        if(word[i]<65||word[i]>96){
            c++;
        }
        else
            index=i;
    }
    if(c==word.length()||c==0)
        return true;
    else if(index==0)
        return true;
    else return false;
    }
};

4.优秀案例

思路一致,代码更加精简

class Solution {
public:
    bool detectCapitalUse(string word) {
        int num_length = word.length();
        int num_count = 0;
        
        for(int i=0;i<num_length;i++){
            if(word[i]>='A' && word[i]<='Z')
                num_count++;
        }
        
        if(num_count==0)
            return true;
        
        if(num_count == num_length)
            return true;
        
        if(word[0]>='A' &&word[0]<='Z' && num_count==1)
            return true;
        
        return false;
        
    }

猜你喜欢

转载自blog.csdn.net/qq_37621506/article/details/83586264