美文网首页
[LeetCode]520. Detect Capital

[LeetCode]520. Detect Capital

作者: Eazow | 来源:发表于2017-05-19 15:56 被阅读58次
    题目

    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用来标记首字母为大写,hasLower标记首字母外有小写字母, hasCapital标记首字母外有大写字母。

    • 如果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
    

    相关文章

      网友评论

          本文标题:[LeetCode]520. Detect Capital

          本文链接:https://www.haomeiwen.com/subject/wvyyxxtx.html