# main idea, compare based on case
# time O(O) spaceO(1)
class Solution:
def detectCapitalUse(self, word: str) -> bool:
up = string.ascii_uppercase
low = string.ascii_lowercase
def helper(word,standard):
for each in word:
if each not in standard:
return False
return True
if word[0] in low and word[-1] in low:
return helper(word,low)
elif word[0] in up and word[-1]:
word = word[1:]
return helper(word,up) or helper(word,low)
else: return False
without helper function, using flag
class Solution:
def detectCapitalUse(self, word: str) -> bool:
n = len(word)
i = 0
cap = False
if word[0].isupper():
cap = True
cnt_low = 0
while i < n:
if i == 0:
cap = word[i].isupper()
if word[i].islower():
cnt_low += 1
i += 1
return (cap and cnt_low == n-1) or (cnt_low == n) or (cap and cnt_low == 0)
solution2
class Solution:
# main idea regex, combine case 2([A-Z]*) and case 3[A-Z][a-z]* ==> .[a-z]*
# time O(N) but highly rely on pattern and implementaion ; space O(1)
def detectCapitalUse(self, word: str) -> bool:
return re.fullmatch(r"[A-Z]*|.[a-z]*",word)