520. Detect Capital

 

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:

  1. All letters in this word are capitals, like “USA”.
  2. All letters in this word are not capitals, like “leetcode”.
  3. 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.

 

这道题给了我们一个单词,让我们检测大写格式是否正确,规定了三种正确方式,要么都是大写或小写,要么首字母大写,其他情况都不正确。那么我们要做的就是统计出单词中所有大写字母的个数cnt,再来判断是否属于这三种情况,如果cnt为0,说明都是小写,正确;如果cnt和单词长度相等,说明都是大写,正确;如果cnt为1,且首字母为大写,正确,其他情况均返回false,参见代码如下:

 

解法一:

class Solution {
public:
    bool detectCapitalUse(string word) {
        int cnt = 0, n = word.size();
        for (int i = 0; i < n; ++i) {
            if (word[i] <= 'Z') ++cnt;
        }
        return cnt == 0 || cnt == n || (cnt == 1 && word[0] <= 'Z');
    }
};

 

下面这种方法利用了STL的内置方法count_if,根据条件来计数,这样使得code非常简洁,两行就搞定了,丧心病狂啊~

 

解法二:

class Solution {
public:
    bool detectCapitalUse(string word) {
        int cnt = count_if(word.begin(), word.end(), [](char c){return c <= 'Z';});
        return cnt == 0 || cnt == word.size() || (cnt == 1 && word[0] <= 'Z');
    }
};

 

参考资料:

https://discuss.leetcode.com/topic/79912/3-lines

https://discuss.leetcode.com/topic/79930/java-1-liner

https://discuss.leetcode.com/topic/80314/6ms-2-lines-c-solution/2

https://discuss.leetcode.com/topic/79911/simple-java-solution-o-n-time-o-1-space

 

LeetCode All in One 题目讲解汇总(持续更新中…) 


转载请注明来源于 Grandyang 的博客 (grandyang.com),欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 grandyang@qq.com

💰


微信打赏


Venmo 打赏

(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,试运营期间前五十位可享受半价优惠~)

×

Help us with donation