Processing math: 100%

熱門文章

2025年4月30日 星期三

ZeroJudge 解題筆記:k515. P3.標題 (Title)

作者:王一哲
日期: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)


C++ 程式碼


使用時間約為 2 ms,記憶體約為 356 kB,通過測試。
#include <iostream>
#include <string>
#include <set>
#include <vector>
#include <algorithm>
#include <cctype>
#include <sstream>
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    set<string> article = {"the", "a", "an", "in", "on",
                           "at", "of", "for", "by", "to",
                           "and", "or", "but"};  // 冠詞、介系詞、連接詞
    string s;
    while(getline(cin, s)) {
        vector<string> word;
        stringstream ss; ss << s;
        while(ss >> s) {
            transform(s.begin(), s.end(), s.begin(), ::tolower);
            word.push_back(s);  // 全部轉成小寫,存成 vector
        }
        int n = (int)word.size();  // 單字數量
        for(int i=0; i<n; i++) {  // 依序讀取單字
            if (i == 0 || i == n-1) {  // 開頭或結尾
                word[i][0] = toupper(word[i][0]);
            } else if (article.count(word[i]) == 0) {  // 如果不是開頭或結尾,且 word[i] 不在 article 之中
                word[i][0] = toupper(word[i][0]);
            }
        }
        for(int i=0; i<n; i++) cout << word[i] << " \n"[i == n-1];
    }
    return 0;
}


沒有留言:

張貼留言