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');
        }
    
  • 相关阅读:
    [CF888G] Xor-mst (Trie 树,最小生成树)
    [JSOI2010]部落划分 (最小生成树)
    [USACO15FEB]Superbull (最小生成树)
    [APIO2009]抢掠计划 ($Tarjan$,最长路)
    [APIO2015] 雅加达的摩天楼 (分块,最短路)
    [USACO07NOV]牛继电器Cow Relays (最短路,DP)
    P1266 速度限制 (最短路,图论)
    C语言编程题目(1)字符串格式化操作 手机键盘次数统计
    MOCTF RE 暗恋的烦恼
    python 面向对象 私有化浅析
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9362054.html
Copyright © 2011-2022 走看看