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');
        }
    
  • 相关阅读:
    【移动端】300ms延迟以及点透事件原因以及解决方案
    javaScript drag对象进行拖拽使用详解
    js文件上传原理(form表单 ,FormData + XHR2 + FileReader + canvas)
    Linux常用bash命令
    一些好的关于网络知识的博客
    python 2 处理HTTP 请求的包
    python 3 处理HTTP 请求的包
    接口测试笔记
    接口测试资料
    PyH : python生成html
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9362054.html
Copyright © 2011-2022 走看看