zl程序教程

您现在的位置是:首页 >  其他

当前栏目

LeetCode笔记:520. Detect Capital

2023-03-15 23:24:11 时间

问题(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. 所有的字母都是大写,比如“USA”。
  2. 所有的字母都不是大写,比如“leetcode”。
  3. 如果有多个字母,只有首字母是大写的,比如“Google”。

否则,我们认为单词没有正确地使用大写。 例1: 输入:“USA” 输出:True 例2: 输入:“FlaG” 输出:False 注意:输入会是一个非空单词,由大小写字母组成。

思路:

没什么取巧的方法,无非是判断三个条件是否成立,要么全是大写,要么只有首字母是大写。

代码(C++):

class Solution {
public:
    bool detectCapitalUse(string word) {
        bool canBig = true;
        int bigNum = 0;
        for (auto c : word) {
            if (c - 'a' < 0) {
                if (!canBig) return false;
                bigNum++;
            }
            else if (c - 'a' >= 0) {
                if (bigNum > 1) return false;
                canBig = false;
            }
        }
        
        return true;
    }
};

或者从大写字母的数量和位置来一起判断:

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

合集:https://github.com/Cloudox/LeetCode-Record