LeetCode: 520 Detect Capital(easy)

题目:

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 class Solution {
 2 public:
 3     bool detectCapitalUse(string word) {
 4         bool result = 1;
 5         if (word[0] < 'a'){
 6             if (word[1] < 'a'){
 7                 for(int i = 2; i < word.size(); i++){
 8                     if(word[i] > 'Z'){
 9                         result = 0;
10                         break;
11                     }
12                 }
13             }
14             else{
15                 for(int i = 2; i < word.size(); i++){
16                     if(word[i] < 'a'){
17                         result = 0;
18                         break;
19                     }
20                 }
21             }
22         }
23         else{
24             for(auto c : word){
25                 if (c < 'a'){
26                     result = 0;
27                     break;
28                 }
29             }
30         }
31         return result;  
32     }
33 };

别人的:

 1 class Solution {
 2 public:
 3     bool detectCapitalUse(string word) {
 4         int cnt = 0;
 5         for(int a = 0; a < word.length(); a++ ) {
 6             if('Z' - word[a] >= 0) 
 7                 cnt++;
 8         }
 9         if(cnt == word.length() || cnt == 0 || (cnt == 1 && ('Z' - word[0] >= 0)))
10             return true;
11         return false;
12         
13     }
14 };

对大写字母计数,然后再判断(全是大写、全是小写、首字母大写)

posted on 2017-08-28 16:26  玲珑子  阅读(98)  评论(0编辑  收藏  举报

导航