b218簡單

105 彰雲嘉區資訊學科能力競賽(2016)|字串反轉

移除最外層一對大括號,再按逗號切成各成員。

解題思路

移除最外層一對大括號,再按逗號切成各成員。

對成員逐字確認是否全在A到Z內;若是則反轉,否則原樣保留。

最後依原順序用逗號串接並加回括號,因此只變動符合條件成員的內部次序。

時間 O(L),空間 O(L)。

Step-by-step animation

教學小例:逐成員驗證全大寫後反轉

回報動畫錯誤
步驟 1 / 3

輸入{AB,A1,aB}

第一項全大寫

第一項全大寫
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    string s;
    cin >> s;
    s = s.substr(1, s.size() - 2);
    stringstream ss(s);
    string t;
    cout << '{';
    bool first = true;
    while (getline(ss, t, ',')) {
        if (all_of(t.begin(), t.end(), [](char c) { return c >= 'A' && c <= 'Z'; }))
            reverse(t.begin(), t.end());
        if (!first)
            cout << ',';
        first = false;
        cout << t;
    }
    cout << "}\n";
}

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

更多