• [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');
        }
    
  • 相关阅读:
    变态跳台阶
    循环删除元素,返回最后一个被删除元素的下标
    阿拉伯数字转中文大写
    最长相同子串
    最多购买种类
    win10 64位 安装scrapy
    requests+正则爬取猫眼电影前100
    Django forms表单 select下拉框的传值
    更改静态图片后,前端依旧显示之前的图片
    阿里云远程连接CentOS
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9362054.html
Copyright © 2020-2023  润新知