[LeetCode] 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');
    }
};

本文转自博客园Grandyang的博客,原文链接:[LeetCode] Detect Capital 检测大写格式,如需转载请自行联系原博主。

相关文章
|
4月前
|
算法 程序员 索引
【Leetcode 程序员面试金典 02.08】 —— 环路检测 |双指针
我们可以使用双指针解决本题,由数学推导可知:a 的距离为(环长度的倍数 - b),即 tmp 指针从头节点走到环开头节点等于 slow 指针走到环开头节点的距离
|
4月前
leetcode:520. 检测大写字母
leetcode:520. 检测大写字母
15 0
|
4月前
|
算法
leetcode-2013:检测正方形
leetcode-2013:检测正方形
26 0
|
4月前
|
Go
golang力扣leetcode 2013.检测正方形
golang力扣leetcode 2013.检测正方形
20 0
|
5月前
|
编译器
【leetcode报错】 leetcode格式问题解决:error: stray ‘\302’ in program [solution.c]
【leetcode报错】 leetcode格式问题解决:error: stray ‘\302’ in program [solution.c]
67 0
|
7月前
【Leetcode -509.斐波那契数 -520.检测大写字母】
【Leetcode -509.斐波那契数 -520.检测大写字母】
29 0
|
9月前
|
算法
LeetCode-2013 检测正方形
LeetCode-2013 检测正方形
|
11月前
|
人工智能 算法 搜索推荐
LeetCode算法小抄 -- 环检测算法 和 拓扑排序算法
LeetCode算法小抄 -- 环检测算法 和 拓扑排序算法
|
API Python
力扣刷题记录——507.完美数、509. 斐波那契数、520. 检测大写字母
力扣刷题记录——507.完美数、509. 斐波那契数、520. 检测大写字母
103 0
力扣刷题记录——507.完美数、509. 斐波那契数、520. 检测大写字母
Leetcode_Python 520 检测大写字母
解题思路 此题只要保证条件成立即可
33 0
Leetcode_Python 520 检测大写字母