LeetCode 520. Delete Capital

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohaibo_/article/details/86410080

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.


v1:模拟

class Solution {
public:
    bool detectCapitalUse(string word) {
        if (word.size() == 1) return true;
        int first = word[0], second = word[1];
        if (first<= 90) {
            // 情况1
            int i = 2;
            if (second <= 90) {
                for (; i < word.size(); i ++ )
                    if (word[i] > 90) break;
            }
            // 情况3
            else {
                for (; i < word.size(); i ++ )
                    if (word[i] <= 90) break;
            }
            if (i != word.size()) return false;
        }
        // 情况2
        else {
            for (auto c : word) {
                if (c <= 90) return false;
            }
        }
        return true;
    }
};

v2:只找从头节点起连续的大写字母的数量

class Solution {
public:
    bool detectCapitalUse(string word) {
        int cnt = 0;
        for(char c: word) if(c <= 90) cnt++;
        return ((cnt==0 || cnt==word.length()) || (cnt==1 && word[0]<=90));
    }
};

猜你喜欢

转载自blog.csdn.net/zhaohaibo_/article/details/86410080