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');
        }
    
  • 相关阅读:
    STM32 -- 硬件知识
    PCIe相关的操作命令
    [转载]PCI/PCIe基础——配置空间
    [转载]网络虚拟化中的 offload 技术:LSO/LRO、GSO/GRO、TSO/UFO、VXLAN
    [转载]TSO、UFO、GSO、LRO、GRO和RSS介绍
    Linux应用函数 -- 字符串
    初级PLC
    中断方式下进行串口通讯的正确方法
    [altium] Altium Designer2013 13.3.4 (10.1881.28608) 完美版
    32个最热CPLD-FPGA论坛
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9362054.html
Copyright © 2011-2022 走看看