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
  • 相关阅读:
    1月10日 TextView
    1月9日 布局2
    30 Adapter适配器
    29 个人通讯录列表(一)
    28 ListView控件
    27 登录模板
    26 Activity的启动模式
    25 Activity的生命周期
    24 得到Activity返回的数据
    23 Activity的传值2(bundle)
  • 原文地址:https://www.cnblogs.com/immjc/p/7149465.html
Copyright © 2011-2022 走看看