LeetCode | 520. Detect Capital

来源:互联网 发布:女子篮球鞋 知乎 编辑:程序博客网 时间:2024/05/24 06:40


Easy题目一次AC^__________________________^


题目:

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.


题意:

判断输入的字符串是否合理使用大写字母,即判断首字母是否为大写,如果是大写,则总共统计的大写字母个数为1或输入子串长度,这种情况下是true;如果首字母为小写,则大写字母个数应该为0,若不满足以上两个约束,则输出false。


代码:

bool detectCapitalUse(string word) {        int len = word.length();        if(len < 1)            return true;        int capital = 0, first = 0;        for(int i = 0; i<len; i++)        {            if(i == 0 && word[i] >= 'A' && word[i] <= 'Z')            {                first = 1;            }            if(word[i] >= 'A' && word[i] <= 'Z')                capital++;        }        if((first && (capital == 1 || capital == len)) || (!first && !capital))            return true;        return false;    }










原创粉丝点击