leetcode解题报告(30):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.

分析

每遇到一个大写字母,就将变量upCount加1,遍历结束后,如果要返回真,那么会满足下列条件之一:

  • upCount == word.size()。即所有字母均为大写
  • upCount == 0.即所有字母均为小写
  • upCount == 1.有且仅有第一个字母为大写。

否则,返回假。

代码如下:

class Solution {
public:
    bool detectCapitalUse(string word) {
        int upCount = 0;
    
        if(word.size() == 0)return false;
        for(int i = 0; i != word.size(); ++i)
             if(isupper(word[i]))++upCount;
        if(upCount == word.size() || upCount == 0 || (upCount == 1 && isupper(word[0])))return true;
        return false;
    }
};

日常水题。。。

posted @ 2017-06-05 22:24  larryking  阅读(189)  评论(0编辑  收藏  举报