题目:
思路:
方法一的解题思路其实很简单,就是判断第一个字母是大写还是小写,如果是大写,那么接下来还要判断第二个字母是大写还是小写,如果是大写,那么后面的都要是大写,用一个while循环来循环判断,如果第二个是小写,那么剩下的一定要都是小写才是正确的,同样也是while循环判断。如果第一个字母就是小写,那么后面的一定都是小写,判断就比较简单,只需要判断是否为小写,小写就继续判断,大写直接返回False
方法二的思路其实也比较简单,和第一个有些类似,也是判断第一个是大写还是小写,如果是小写,直接按照方法一的判断就可以,如果是大写,则统计大写字母的个数,要么是1(也就是第一个字母是大写),要么就等于字符串的长度,这样才是正确的,否则就是错的,根据conut值来返回判断结果。
在这里我写了两种方法来解决,在内存消耗上相差不多,但是时间上还是有一定的提高,第二种方法更好理解一些。
方法一:
class Solution:
def detectCapitalUse(self, word: str) -> bool:
# 根据第一个字母是大写还是小写来进行判断
index = 0
key = word[index]
if key>='A' and key <='Z': # 第一个字母是大写
index = index + 1 # index+1 到下标为1处,也就是第二个字母
if index<len(word):
key = word[index]
if key>='A' and key <='Z': # 第二个字母也是大写 就判断是否剩下的都是大写
while index<len(word):
key = word[index] # key = 当前第二个字母
if key>='A' and key <='Z':
index = index + 1
else:
return False
return True
else:
while index<len(word):
key = word[index] # key = 当前第二个字母
if key>='a' and key <='z':
index = index + 1
else:
return False
return True
else:
return True
else: # 第一个字母是小写
while index < len(word):
key = word[index]
if key>='a' and key<='z':
index = index + 1
else:
return False
return True
方法二:
class Solution:
def detectCapitalUse(self, word: str) -> bool:
# 根据第一个字母是大写还是小写来进行判断
index = 0
count=0
if word[index]>='A' and word[index] <='Z':
count+=1
index+=1
while index < len(word):
if word[index]>='A' and word[index]<='Z':
count+=1
index+=1
if count==1 or count == len(word):
return True
else:
return False
else: # 第一个字母是小写
while index < len(word):
if word[index]>='a' and word[index]<='z':
index+=1
else:
return False
return True
关于LeetCode的解题方法欢迎大家一起讨论~