題目連結: https://leetcode.com/problems/detect-capital/description/
題意說明: 如果字串全部大寫,字首大寫或全小寫,那麼就是 True,其他情況就是 False
初始想法
感覺可以分別用函式解決
全大寫: upper()
字首大寫: word.capitalize()
全小寫: lower()
class Solution:
def detectCapitalUse(self, word: str) -> bool:
return word == word.upper() or word == word.lower() or word == word.capitalize()
表現還算不錯,但不穩定,有些 Test Case會很慘
參考他人作法
- 將三次判斷融合成一次判斷
- 將 capitalize()換成 title()
class Solution:
def detectCapitalUse(self, word: str) -> bool:
return word in [word.upper(), word.lower(), word.title()]
結果差不多但相對簡潔好讀,但 title()沒有什麼顯著影響。
2024–09–12
可以更簡化成 is判斷 function,isupper, islower, istitle
class Solution:
def detectCapitalUse(self, word: str) -> bool:
return word.isupper() or word.islower() or word.istitle()
計算大寫的字母數量
- 沒有大寫
- 全大寫
- 1個大寫且是字首大寫
class Solution:
def detectCapitalUse(self, word: str) -> bool:
Capital_Count = 0
for w in word:
if w.isupper():
Capital_Count = Capital_Count + 1
return Capital_Count == 0 or Capital_Count == len(word) or (Capital_Count == 1 and word[0].isupper())