a604簡單區分大小寫的字母頻率
CPE:What’s The Frequency, Kenneth? (UVa 499)
保留逐行邊界,依指定字母順序列出最高頻率。
解題思路
每行建立 52 個字母的計數,大寫 A–Z 與小寫 a–z 分開;空白、數字及標點都略過。掃完後求最大頻率,再按照大寫優先、小寫其次的順序收集所有同頻字母。
使用 getline 或逐行迭代,不可把整份輸入以空白切開,因為每行是獨立問題。將同頻字母直接串接,再印一個空白與頻率。若一行沒有英文字母,程式採空字母串加 0 的自然延伸;本地題敘未額外定義該情況。
Step-by-step animation
示意:AaA bb!
步驟 1 / 3
計數大寫
兩個 A 都記入同一格。
A:2
a:0
b:0
- A
- 2
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main() {
string s, letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
while (getline(cin, s)) {
int count[52] = {};
for (char ch : s) {
size_t p = letters.find(ch);
if (p != string::npos)
++count[p];
}
int best = *max_element(count, count + 52);
string answer;
if (best)
for (int i = 0; i < 52; ++i)
if (count[i] == best)
answer += letters[i];
cout << answer << ' ' << best << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。