ZeroJudge D267: Letter Frequency

題目敘述

每筆測資第一行有一個正整數N,接下來會有N行,每行會有一個包含空格字元的字串。要求輸出出現次數最多的英文字母,大小寫視為同一個字母,輸出時請輸出小寫,如果有出現次數相同的情況則由小到大輸出。


範例輸入 #1

1

Computers account for only 5% of the country's commercial electricity consumption.


範例輸出 #1

co


解題思路

先將每個字母出現的次數存放到一個Map中,接下來用Auto跑這個Map的For迴圈,並且再開一個新的Map (Key是int,Value是Vector<char>)。將舊的Map中的值乘以-1當作是新的Map的Key,並將字元Push_Back到新的Map的Value中。之後一樣用Auto跑新的Map的For迴圈,先將Vector進行排序後將裡面的字母輸出,然後就可以Break這個For迴圈因為只要輸出最多次數的字母而已。

解題程式碼如下 (僅供參考):

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    int N;
    cin >> N;
    string a;
    getline(cin, a);
    for (int i = 0; i<N; i++)
    {
        string str;
        getline(cin, str);
        map<char, int>MAP;
        for (int j = 0; j<str.length(); j++)
        {
            if (isalpha(str[j]))
            {
                MAP[tolower(str[j])]++;
            }
        }
        map<int, vector<char>>ans;
        for (auto it:MAP)
        {
            ans[it.second * -1].push_back(it.first);
        }
        for (auto it:ans)
        {
            sort(it.second.begin(), it.second.end());
            for (int j = 0; j<it.second.size(); j++)
            {
                cout << it.second[j];
            }
            cout << "\n";
            break;
        }
    }
}

留言

這個網誌中的熱門文章

ZeroJudge M933: 邏輯電路

ZeroJudge A148: You Cannot Pass?!

ZeroJudge A263: 日期差幾天