zoukankan      html  css  js  c++  java
  • 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 };

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

  • 相关阅读:
    n的阶乘
    二叉树遍历
    二分查找练习
    字符串中最长回文序列求解
    复数集合
    AppCrawler自动化遍历使用详解(版本2.1.0 )(转)
    谷歌驱动下载链接
    谷歌浏览器插件
    Pycharm破解方法
    go学习链接
  • 原文地址:https://www.cnblogs.com/llxblogs/p/7444406.html
Copyright © 2011-2022 走看看