前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:520. Detect Capital

LeetCode笔记:520. Detect Capital

作者头像
Cloudox
发布2021-11-23 16:28:24
2880
发布2021-11-23 16:28:24
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题(Easy):

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.

大意:

给出一个单词,你需要判断其大写的使用是否正确。 我们定义单词中大写的用法在下面的情况下是正确的:

  1. 所有的字母都是大写,比如“USA”。
  2. 所有的字母都不是大写,比如“leetcode”。
  3. 如果有多个字母,只有首字母是大写的,比如“Google”。

否则,我们认为单词没有正确地使用大写。 例1: 输入:“USA” 输出:True 例2: 输入:“FlaG” 输出:False 注意:输入会是一个非空单词,由大小写字母组成。

思路:

没什么取巧的方法,无非是判断三个条件是否成立,要么全是大写,要么只有首字母是大写。

代码(C++):

代码语言:javascript
复制
class Solution {
public:
    bool detectCapitalUse(string word) {
        bool canBig = true;
        int bigNum = 0;
        for (auto c : word) {
            if (c - 'a' < 0) {
                if (!canBig) return false;
                bigNum++;
            }
            else if (c - 'a' >= 0) {
                if (bigNum > 1) return false;
                canBig = false;
            }
        }
        
        return true;
    }
};

或者从大写字母的数量和位置来一起判断:

代码语言:javascript
复制
class Solution {
public:
    bool detectCapitalUse(string word) {
        int cnt = 0;
        for(char c: word) if('Z' - c >= 0) cnt++;
        return ((cnt==0 || cnt==word.length()) || (cnt==1 && 'Z' - word[0]>=0));
    }
};

合集:https://github.com/Cloudox/LeetCode-Record

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/1/24 上,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题(Easy):
  • 大意:
  • 思路:
  • 代码(C++):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档