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

    1. All letters in this word are capitals, like "USA".
    2. All letters in this word are not capitals, like "leetcode".
    3. 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.

    检测单词大小写规范,题目要求3个判断标准,通过条件判断每一个单词即可。这里使用一个计数变量来统计每个单词中小写字母出现的次数。

    class Solution {
    public:
        bool detectCapitalUse(string word) {
            int cnt = 0;
            int n = word.size();
            for (char c : word) 
                if (c >= 'a' && c <= 'z')
                    cnt++;
            if (cnt == 0 || cnt == n)
                return true;
            int tmp = 0;
            if (word[0] >= 'A' && word[0] <= 'Z')
                for (int i = 1; i != n; i++) {
                    if (word[i] >= 'a' && word[i] <= 'z')
                        tmp++;
                }
            if (tmp + 1 == n)
                return true;
            return false;
        }
    };
    // 9 ms
  • 相关阅读:
    VIM 编辑器命令
    Ubuntu LAMP 便捷配置
    Linux基础命令
    Sql sever 定时任务设置
    C#自动发送邮件
    序列化与反序列化
    字符串.特殊引用类型
    抽象方法、接口
    函数的返回值
    线程
  • 原文地址:https://www.cnblogs.com/immjc/p/7149465.html
Copyright © 2011-2022 走看看