a201簡單字串、字元與格式解析

TOI 2020/12 新手組:英文縮寫

每個單字先判特殊替換,否則取大寫首字母。

前往題目練習 →回報教學錯誤總字元數 L:時間 O(L),空間 O(L)。

這題在學什麼

按空白切出單字,保持原先順序。

將單字轉小寫後檢查 for、to、and、you,分別產生 4、2、n、u。

其他單字取原首字母的大寫,最後將結果直接串接,沒有分隔空白。

Step-by-step animation

英文縮寫・特殊字典與首字母

回報動畫錯誤
步驟 1 / 3

一般字首

Time 取首字 T。

Time→T
answer
T

Reference solution

回報程式錯誤

完整程式

#include <cctype>
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    map<string, string> special = {{"for", "4"}, {"to", "2"}, {"and", "n"}, {"you", "u"}};
    string w, ans;
    while (cin >> w) {
        string low = w;
        for (char &c : low)
            c = (char)tolower((unsigned char)c);
        if (special.count(low))
            ans += special[low];
        else
            ans += (char)toupper((unsigned char)w[0]);
    }
    cout << ans << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多