[LeetCode]520. Detect Capital

題目

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.

難度

Easy

方法

firstIsCapital用來(lái)標(biāo)記首字母為大寫,hasLower標(biāo)記首字母外有小寫字母, hasCapital標(biāo)記首字母外有大寫字母。

  • 如果hasLowerhasCapital都為True,則返回False
  • 如果首字母為小寫,hasCapitalTrue,則返回False
  • 其余情況返回True
python代碼
class Solution(object):
    def detectCapitalUse(self, word):
        length = len(word)

        firstIsCapital = word[0].isupper()
        i = 1
        hasLower = False
        hasCapital = False
        while i < length:
            if word[i].islower():
                hasLower = True
            else:
                hasCapital = True
            if hasLower and hasCapital:
                return False
            i += 1

        if not firstIsCapital and hasCapital:
            return False

        return True

"""
    def detectCapitalUse(self, word):
        capitalsCount = 0
        for i in range(len(word)):
            if word[i].isupper():
                capitalsCount += 1

        if capitalsCount==0 or capitalsCount==len(word) or (capitalsCount==1 and word[0].isupper()):
            return True
        return False
"""

assert Solution().detectCapitalUse("USA") == True
assert Solution().detectCapitalUse("FlaG") == False
assert Solution().detectCapitalUse("ABc") == False
assert Solution().detectCapitalUse("Leetcode") == True
assert Solution().detectCapitalUse("aBC") == False
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,905評(píng)論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,056評(píng)論 0 23
  • 12時(shí)急診入院。 患者訴右上腹及腰背部劇烈疼痛,呈強(qiáng)迫體位,急性病容。查體:T:36.7℃,P:70次/分,BP:...
    風(fēng)花雪月下苦讀閱讀 708評(píng)論 0 0
  • 我一直想弄明白我是誰(shuí),如果從外界給我一個(gè)定義,我的名字叫王鄂,這是我父母給我的代碼,我出生自農(nóng)村,感受過(guò)農(nóng)村生活的...
    王楓浚閱讀 236評(píng)論 1 1
  • “一個(gè)好的習(xí)慣可以給人帶來(lái)億萬(wàn)的財(cái)富,但億萬(wàn)的財(cái)富卻不一定買得來(lái)一個(gè)好習(xí)慣”。習(xí)慣由知識(shí)、技巧以及意愿三方面...
    李白馬閱讀 569評(píng)論 0 1

友情鏈接更多精彩內(nèi)容