題目
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
用來(lái)標(biāo)記首字母為大寫鉴逞,hasLower
標(biāo)記首字母外有小寫字母奕污, hasCapital
標(biāo)記首字母外有大寫字母。
- 如果
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