日期:2025年4月30日
ZeroJudge 題目連結:k515. P3.標題 (Title)
解題想法
我先將所有要小寫的冠詞、介系詞、連接詞存入一個陣列或集合中,並將讀進來的字串全部轉成小寫字母存入陣列,由陣列依序讀取每個單字,如果是整行的開頭或結束則將開頭字母大寫;如果是中間的單字,再檢查這個單字是否為冠詞、介系詞、連接詞,如果不是,則將開頭字母改成大寫。
Python 程式碼
使用時間約為 20 ms,記憶體約為 3.3 MB,通過測試。
import sys
article = ("the", "a", "an", "in", "on",
"at", "of", "for", "by", "to",
"and", "or", "but") # 冠詞、介系詞、連接詞
for line in sys.stdin:
word = line.lower().split() # 全部轉成小寫,用空格分隔,存成串列
n = len(word) # 單字數量
for i in range(n): # 依序讀取單字
if i == 0 or i == n-1: # 開頭或結尾
word[i] = word[i][0].upper() + word[i][1:]
elif word[i] not in article: # 如果不是開頭或結尾,且 word[i] 不在 article 之中
word[i] = word[i][0].upper() + word[i][1:]
print(*word)