[LeetCode]520. Detect Capital

2017-05-19  本文已影响58人  Eazow
题目

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标记首字母外有大写字母。

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
上一篇 下一篇

猜你喜欢

热点阅读