熱門文章

2025年11月15日 星期六

ZeroJudge 解題筆記:i121. 英文字母大小寫的抉擇

作者:王一哲
日期:2025年11月15日


ZeroJudge 題目連結:i121. 英文字母大小寫的抉擇

解題想法


這題應該是專門出給 Python 的題目,因為 Python 的字串內建 capitalize(), upper(), title(), lower() 這四種格式,如果要用 C++ 寫這題會很麻煩。

Python 程式碼


使用時間約為 15 ms,記憶體約為 3 MB,通過測試。
line = input()
style = int(input())
if style == 1:
    print(line.capitalize())
elif style == 2:
    print(line.upper())
elif style == 3:
    print(line.title())
else:
    print(line.lower())


C++ 程式碼


使用時間約為 2 ms,記憶體約為 340 kB,通過測試。
#include <iostream>
#include <string>
#include <cctype>  // for toupper, tolower
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    string s; getline(cin, s);
    int n = (int)s.size();
    int style; cin >> style;
    if (style == 1) {
        bool upper = true;
        for(int i=0; i<n; i++) {
            char c = s[i];
            if (isalpha(c)) {
                if (upper) c = toupper(c);
                else c = tolower(c);
                upper = false;
            }
            cout << c << (i == n-1 ? "\n" : "");
        }
    } else if (style == 2) {
        for(int i=0; i<n; i++) {
            char c = s[i];
            if (isalpha(c)) c = toupper(c);
            cout << c << (i == n-1 ? "\n" : "");
        }
    } else if (style == 3) {
        bool upper = true;
        for(int i=0; i<n; i++) {
            char c = s[i];
            if (isalpha(c)) {
                if (upper) c = toupper(c);
                else c = tolower(c);
                upper = false;
            } else {
                upper = true;
            }
            cout << c << (i == n-1 ? "\n" : "");
        }
    } else {
        for(int i=0; i<n; i++) {
            char c = s[i];
            if (isalpha(c)) c = tolower(c);
            cout << c << (i == n-1 ? "\n" : "");
        }
    }
    return 0;
}


沒有留言:

張貼留言