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:

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.

思路

统计字符串中的大写字母数量,且用flag记录首位字符是否是大写字母。如果大写字母数量等于0或字符总数,返回true;如果大写字母数量为1,且flag为1(该大写字母在首位),返回true;其他返回false。

代码

class Solution {
public:
    bool detectCapitalUse(string word) {
        int n=word.size();
        int m=0;
        int flag=0;
        for(int i=0;iif(word[i]>='A'&&word[i]<='Z')
            {
                m++;
                if(i==0)
                    flag=1;
            }
        }
        if(m==n||m==0)
            return true;
        else if(m==1)
        {
            if(flag)
                return true;
            else
                return false;
        }
        else
            return false;
    }
};

你可能感兴趣的:(刷题,刷题笔记)