520. Detect Capital

  • Hardness: \(\color{green}\textsf{Easy}\)
  • Ralated Topics: String

一、題目

We define the usage of capitals in a word to be right when one of the following cases holds:

  • All letters in this word are capitals, like "USA".
  • All letters in this word are not capitals, like "leetcode".
  • Only the first letter in this word is capital, like "Google".
    Given a string word, return true if the usage of capitals in it is right.

Example 1:

  • Input: word = “USA”
  • Output: true

Example 2:

  • Input: word = FlaG"
  • Output: false

Constraints:

  • 1 <= word.length <= 100
  • word consists of lowercase and uppercase English letters.

二、分析

  • 這題只需要判斷簡單的 if-else 即可解題。
  • 根據題意,要馬全是大寫,要馬全是小寫,不然就是只有首字大寫。

三、解題

1. String

  • Time complexity: \(O(n)\)
  • Space complexity: \(O(1)\)
bool detectCapitalUse(string word) {
    if (word.length() == 1) return true;
    if (word[0] >= 'a') {                   // 小寫
        for (int i = 1; i < word.length(); i++){
            char& c = word[i];
            if (c < 'a') return false;
        } 
    } else {                                // 大寫
        if (word[1] < 'a') {                // 大寫+大寫
            for (int i = 2; i < word.length(); i++) {
                char& c = word[i];
                if (c >= 'a') return false;
            }
        } else {                            // 大寫+小寫
            for (int i = 2; i < word.length(); i++) {
                char& c = word[i];
                if (c < 'a') return false;
            }
        }
    }
    return true;
}

回目錄 Catalog