[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

 

posted @ 2017-07-11 10:53  immjc  阅读(126)  评论(0编辑  收藏  举报