a755簡單英文字母正規化與頻率排序

CPE:What’s Cryptanalysis? (UVa 10008)

跨多行統計不分大小寫的英文字母。

前往題目練習 →回報教學錯誤文字總長 L,時間 O(L+26 log 26),統計/排序工作空間 O(26);C++ 另保存最長輸入行 O(H),Python 另有整份輸入緩衝 O(T),H、T 分別為最長行與全部輸入長度。

解題思路

將 a–z 轉為 A–Z,只有落在英文字母範圍的字元才更新 26 格計數。這裡不應使用廣泛的 Unicode 字母分類,因為題目只計英文字母。空白、數字、標點全部忽略。

把有出現的字母依 (−次數,字母) 排序,先印最常見者,同次數時字母小者先印。第一行 n 表示後續恰好 n 行,即使中間有空行也占一行;不能用空行作為終止條件,也不應把 n 本身納入統計。

Step-by-step animation

示意:文字 aB b!

回報動畫錯誤
步驟 1 / 3

處理 aB

a 正規化為 A,B 維持 B。

A:1
B:1
有效字母
2

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
    int n;
    cin >> n;
    string s;
    getline(cin, s);
    int f[26] = {};
    while (n--) {
        getline(cin, s);
        for (char c : s) {
            if (c >= 'a' && c <= 'z')
                c -= 32;
            if (c >= 'A' && c <= 'Z')
                ++f[c - 'A'];
        }
    }
    vector<int> a;
    for (int i = 0; i < 26; ++i)
        if (f[i])
            a.push_back(i);
    sort(a.begin(), a.end(), [&](int x, int y) { return f[x] != f[y] ? f[x] > f[y] : x < y; });
    for (int i : a)
        cout << char('A' + i) << ' ' << f[i] << '\n';
}

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

更多