zoukankan      html  css  js  c++  java
  • [LeetCode] 520. 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:

    All letters in this word are capitals, like "USA".
    All letters in this word are not capitals, like "leetcode".
    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.首字母大写,其他小写
    2.全小写
    3.全大写

    写个函数判断单词格式是否正确

    我是想着用逻辑运算来搞,代码很简单,也用不着注释了

    bool detectCapitalUse(string word)
    {
        bool allUpper = true;
        bool allLower = true;
        bool firstUpper = false;
    
        if (word[0] >= 'A' && word[0] <= 'Z')
        {
            firstUpper = true;
        }
    
        for (int i = 0; i < word.length(); i++)
        {
            if (word[i] >= 'A' && word[i] <= 'Z')
            {
                allUpper = allUpper && 1;
                allLower = allLower && 0;
                if (i != 0)
                {
                    firstUpper = firstUpper && 0;
                }
            }
            else
            {
                allUpper = allUpper && 0;
                allLower = allLower && 1;
                firstUpper = firstUpper && 1;
            }
        }
    
        return allUpper || allLower || firstUpper;
    }
    

    再看看LeetCode上大佬的代码

    直接判断单词中大写字母个数,单词格式合法有三种情况
    1.0各大写字母(全小写)
    2.1各大写字母且在第一个
    3.大写字母数量==单词长度

    bool detectCapitalUse(string word) {
            int count = 0;
            for (auto c : word) {
                if (c <= 'Z')
                    count++;
            }
            return count == word.size() || count == 0 || (count == 1 && word[0] <= 'Z');
        }
    
  • 相关阅读:
    spring分布式事务学习笔记
    大家说说看针对微信的这个限制,如何吐槽????
    Easy-Mock 一个H5前端接口模拟神器
    CSS设计模式之三权分立模式篇 ( 转)
    引爆你的Javascript代码进化 (转)
    基于jQuery的软键盘
    基于jQuery的数字键盘插件
    支持触屏的zepto轮播图插件
    支持触屏的jQuery轮播图插件
    基于CSS3的3D旋转效果
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9362054.html
Copyright © 2011-2022 走看看