[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用来标记首字母为大写,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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容