Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 520. Detect Capital #520

Open
grandyang opened this issue May 30, 2019 · 0 comments
Open

[LeetCode] 520. Detect Capital #520

grandyang opened this issue May 30, 2019 · 0 comments

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019

 

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 题目讲解汇总(持续更新中...) 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant