CPE 一顆星選集 49 道必考題
題目連結:https://zerojudge.tw/ShowProblem?problemid=e507
內容
給定兩個由小寫字母組成的字串,印出兩字串共同擁有的字母(可重複),按照字母順序排列。
範例輸入
pretty
women
walking
down
the
street
範例輸出
e
nw
et
想法
使用兩個陣列分別計算兩字串字母出現次數,使 a 對應到 0 、 b 對應到 1 … z 對應到 25,設 wa 陣列表示 a 字串字母出現次數,則 wa[2] = 5 代表 c 在此字串中出現 5 次。
最後由 0 (a) 掃到 25 (z),檢查此字母是否同時在兩字串中出現,若是,則更新兩陣列數值,並且輸出此字母,直到其中一方為 0 ,接著檢查下一個字母,到 z 為止。
程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include <bits/stdc++.h> #define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr) using namespace std;
int main(){ fastio; string a, b; int wa[26], wb[26]; while(cin >> a >> b){ memset(wa, 0, sizeof(wa)); memset(wb, 0, sizeof(wb)); for(int i = 0; i < a.length(); ++i) ++wa[a[i]-'a']; for(int i = 0; i < b.length(); ++i) ++wb[b[i]-'a']; for(int i = 0; i < 26; ++i){ while(wa[i] != 0 && wb[i] != 0){ cout << char(i+'a'); --wa[i], --wb[i]; } } cout << "\n"; } }
|