520. Detect Capital

来源:互联网 发布:冒险岛游戏数据库系统 编辑:程序博客网 时间:2024/06/04 00:20

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.


包括构思什么的想了三四个小时,思路可能不是很好,根据第一个字符和第二个字符的大小写排除三种不合法情况。

开始在return false 后面加了 break  后来发现是多余的,加break就是错的

class Solution {public:    bool detectCapitalUse(string word) {        int a=word.length();               if(word[0]>='a')        {                             for (int i=1;i<a;i++)               {                         if(word[i]<'a')   return false;                                   }            return true;        }                         if(word[0]<'a'&&word[1]<'a' )          {              for (int i=2;i<a;i++)               {                         if(word[i]>='a')   return false;                                        }           return true ;        }                if(word[0]<'a'&&word[1]>='a' )         {            for (int i=2;i<a;i++)               {                         if(word[i]<'a')   return false;                                   }            return true;          }                                   }      };


发现一个简单点的答案(思路一样,我忘了 isupper 和 islower):

题目大意:判断一个字母是否大小写正确:要么全是大写,要么全是小写,或者首字母大写其他小写,否则不满足题意~
分析:判断word[0]和word[1]的大小写,如果word[0]是小写,那后面必须是小写,如果word[0]是大写word[1]是小写,那后面也必须是小写,如果word[0]是大写word[1]也是大写那么后面必须都是大写~

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

后来更巧妙的一个答案:

这道题给了我们一个单词,让我们检测大写格式是否正确,规定了三种正确方式,要么都是大写或小写,要么首字母大写,其他情况都不正确。那么我们要做的就是统计出单词中所有大写字母的个数cnt,再来判断是否属于这三种情况,如果cnt为0,说明都是小写,正确;如果cnt和单词长度相等,说明都是大写,正确;如果cnt为1,且首字母为大写,正确,其他情况均返回false,参见代码如下:

 

解法一:

复制代码
class Solution {public:    bool detectCapitalUse(string word) {        int cnt = 0, n = word.size();        for (int i = 0; i < n; ++i) {            if (word[i] <= 'Z') ++cnt;        }        return cnt == 0 || cnt == n || (cnt == 1 && word[0] <= 'Z');    }};
复制代码

 


 


原创粉丝点击