We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
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:
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 题目讲解汇总(持续更新中...)
The text was updated successfully, but these errors were encountered:
No branches or pull requests
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:
Otherwise, we define that this word doesn't use capitals in a right way.
Example 1:
Example 2:
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
这道题给了我们一个单词,让我们检测大写格式是否正确,规定了三种正确方式,要么都是大写或小写,要么首字母大写,其他情况都不正确。那么我们要做的就是统计出单词中所有大写字母的个数cnt,再来判断是否属于这三种情况,如果cnt为0,说明都是小写,正确;如果cnt和单词长度相等,说明都是大写,正确;如果cnt为1,且首字母为大写,正确,其他情况均返回false,参见代码如下:
解法一:
下面这种方法利用了STL的内置方法count_if,根据条件来计数,这样使得code非常简洁,两行就搞定了,丧心病狂啊~
解法二:
参考资料:
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 题目讲解汇总(持续更新中...)
The text was updated successfully, but these errors were encountered: