String:520. Detect Capital
程序员文章站
2022-03-09 22:38:15
...
我的方法:很常规,设一个count记录大写字母的个数,如果是0,则true;如果是1,则返回第一个字符是否是true;如果等于总字符数,返回true,其他情况都是false。
class Solution {
public:
bool detectCapitalUse(string word) {
int count = 0;
for(int i = 0; i < word.size(); ++i)
{
if(word[i] >= 'A' && word[i] <= 'Z')
{
count++;
}
}
if(count == 0)
return true;
if(count == 1)
return word[0] >= 'A' && word[0] <= 'Z';
if(count == word.size())
return true;
return false;
}
};
但是判断大写字母这里,我写的太啰嗦,其实有个isupper(s[i])函数更快更好用!
还看到一种我不会的写法:
class Solution {
public:
bool detectCapitalUse(string word) {
int capCnt = count_if(word.begin(), word.end(), [](char c){return c <= 'Z';});
return !capCnt || capCnt == word.size() || (capCnt == 1 && word[0] <= 'Z');
}
};
用到了count_if函数:
bool greater10(int value)
{
return value >10;
}
//...
result1 = count_if(v1.begin(), v1.end(), greater10);
推荐阅读
-
LeetCode - 520 - 检测大写字母(detect-capital)
-
Java/520. Detect Capital 检测大写字母
-
[高级编程技术作业]LeetCode Problem 520. Detect Capital
-
Leetcode 520. Detect Capital (python+cpp)
-
Leetcode PHP题解--D81 520. Detect Capital
-
Leetcode PHP题解--D81 520. Detect Capital
-
520. Detect Capital
-
String:520. Detect Capital
-
LeetCode--Python解析【Detect Capital】(520)
-
【String-easy】520. Detect Capital 检查是否是Capital