题目
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:
- 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 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标记首字母外有大写字母。
- 如果hasLower和hasCapital都为True,则返回False
- 如果首字母为小写,hasCapital为True,则返回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
