Leetcode刷题78-520. 检测大写字母(C++详细解法!!!)

Come from : [https://leetcode-cn.com/problems/detect-capital/]

520. Detect Capital

  • 1.Question
  • 2.Answer
  • 3.大神们的解决方案
  • 4.我的收获

1.Question

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

Note :

The input will be a non-empty word consisting of uppercase and lowercase latin letters.

2.Answer

easy 类型题目。不多BB。。。

class Solution {
public:
    bool detectCapitalUse(string word) {
        int count = 0;
        for(auto c : word)
        {
            if(c >= 'A' && c<= 'Z')
            {
                ++count;
            }
        }
        if(count == word.size() || count == 0 )
        {
            return true;
        }
        else if( count == 1 && (word[0] >= 'A' && word[0] <= 'Z') )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

3.大神们的解决方案

class Solution {
public:
    bool low(char i){
        return i<='z'&&i>='a';
    }
    bool detectCapitalUse(string word) {
        int L=word.size(),sum=0;
        bool fir=low(word[0]);
        for(int i=1;i<L;i++)
            sum+=low(word[i]);
        return (fir+sum==0)||(fir+sum==L)||(fir==0&&sum==L-1);
    }
};

4.我的收获

Fighting~~~

2019/5/14 胡云层 于南京 78

你可能感兴趣的:(LeetCode从零开始,LeetCode,C++)