520. Detect Capital
原创
©著作权归作者所有:来自51CTO博客作者mb6304a73bed12a的原创作品,请联系作者获取转载授权,否则将追究法律责任
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.
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)
如果不偷懒,不用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