博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Detect Capital 检测大写格式
阅读量:7116 次
发布时间:2019-06-28

本文共 1416 字,大约阅读时间需要 4 分钟。

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的博客,原文链接:,如需转载请自行联系原博主。

你可能感兴趣的文章
t - sql的阶梯:超越基础水平9:动态t - sql代码
查看>>
第十一周进度条
查看>>
1140 - How Many Zeroes?
查看>>
【 一次性密码】TOTP
查看>>
java多线程细微知识点
查看>>
文档对象模型DOM(二)
查看>>
【Single Num II】cpp
查看>>
【 Sqrt(x) 】cpp
查看>>
第十七章: 自定义View
查看>>
从两个数组中查找相同的数字谈Hashtable
查看>>
201671010136 泛型类总结
查看>>
各种标志位的含义
查看>>
UitraEdit快捷键
查看>>
实现一个通用分页查询接口
查看>>
00 EPLAN安装问题
查看>>
YUV格式
查看>>
linux命令 ip
查看>>
Ubuntu使用apt-get upgrade升级时出错
查看>>
【python】-- RabbitMQ 队列消息持久化、消息公平分发
查看>>
Trace Application Engine Processes Using Process Definitions
查看>>