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.

Python字符串有两个方法:isupper()和islower() 可以判断字符串是否为小写/大写。如果用这个方法,则程序为:

class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
return word is not None and ( \
word.isupper() or \
word.islower() or \
(word[0].isupper() and word[1:].islower()))


# word = "USA"
# word = 'leetcode'
# word = 'Google'
word = 'FlaG'
r = Solution().detectCapitalUse(None)
print(r)

520. Detect Capital_大小写

如果不偷懒,不用Python自带的方法,那么需要自己写函数判断是否是大小写。程序如下:

class Solution(object):

def ifAllUpper(self, word):
for i in word:
if i >= 'a' and i <= 'z':
return False
return True

def ifAllLower(self, word):
for i in word:
if i >= 'A' and i <= 'Z':
return False
return True

def ifOnlyFirstUpper(self, word):
return self.ifAllUpper(word[0]) and self.ifAllLower(word[1:])

def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
return word is not None and ( \
self.ifAllUpper(word) or \
self.ifAllLower(word) or

520. Detect Capital_python_02