Leetcode 520. Detect Capital 发现大写词 (字符串处理)

题目描述

已知一个单词,你需要给出它是否为"大写词" 我们定义的"大写词"有下面三种情况:

  1. 所有字母都是大写,比如"USA"
  2. 所有字母都不是大写,比如"leetcode"
  3. 只有第一个字母是大写,比如"Google"

测试样例

Input: "USA"
Output: True

Input: "FlaG"
Output: False

详细分析

水题,按照上面定义的三种情况写代码即可。 稍微值得注意的是如果字符串为空输出是true

代码实现

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

猜你喜欢

转载自blog.csdn.net/u013524455/article/details/79363870