close
Content

我們對一個問題有興趣,到底在這行文字中頻率最高的字母是什麼? 

 可以忽略一些非字母的文字,要注意的是若是出現了A大寫字母跟a小寫都算是a。

 

Input

第一個是代表有幾個測試資料。

一行就是一個測試資料,這一行可能有空白,但是至少有一個字母,一行全部的字母加起來不超過200個

Output
對每個測試資料,輸出頻率最高的小寫字母。(如果超過兩個一樣,請字典由小排到大)
Sample Input #1
1
Computers account for only 5% of the country's commercial electricity consumption.
Sample Output #1
co
測資資訊:
記憶體限制: 512 MB
公開 測資點#0 (100%): 1.0s , <1M

C++一版:

/*找出頻率最高數字*/
#include <iostream>
using namespace std;

int main()
{
    int t;
    string s;
    cin>>t;
    getline(cin,s);
    while (t--)
    {
        int alphabet[26]={0}; //這裡一定要括弧!!! 不可以只寫int alphabet[26],他裡面指標會亂跑 
        getline(cin,s);
        int most=0;
        for (int i = 0; i < s.size(); i++){
            /*檢查每個單字時,在對應的array+1,同時也去比較是否最大值*/
            int index=-1;

            if (s[i]>='A' and s[i]<='Z'){index = s[i] - 'A';} // index = s[i] - 'A';字母對映的位置
            if (s[i]>='a' and s[i]<='z'){index = s[i] - 'a';} // index = s[i] - 'a';字母對映的位置

            /*index找出來後,對映位置+1,同時比較最大值*/
            if (index>-1){
                alphabet[index]++;
                most=max(most,alphabet[index]);}           
        }
        /*--------------------------------------------------------*/
        for (int i = 0; i < 26; i++){
            if (alphabet[i]==most){
                cout<<(char)('a'+i); //(char)('a'+i)把數字轉成字元
            }
            
        }
        cout<<"\n";  
    }
    return 0;

}

C++ˋ二版: (參考 https://yuihuang.com/zj-d267/):

/*找出頻率最高數字*/
#include <iostream>
#include <map> //類似py的dic
using namespace std;

int main()
{
    int n;
    string s;
    cin>>n;
    getline(cin,s);
    while (n--)
    {
        getline(cin,s);
        map<char,int> mp;
        int most=0;
        for (int i = 0; i < s.size(); i++){

            if (s[i] >= 'a' && s[i] <= 'z'){ 
                mp[s[i]]++;                 //若為小寫,建立一個字典{"s[i]":+1}
                most=max(most,mp[s[i]]);    //檢查最多次數
            }
            if (s[i] >= 'A' && s[i] <= 'Z'){
                s[i] = 'a' + (s[i] - 'A'); //把大寫轉小寫
                mp[s[i]]++;                //一樣建立一個字典{"s[i]":+1}
                most=max(most,mp[s[i]]);   //檢查最多次數
            }
        }

        for(auto i:mp){ //auto:讓電腦字東偵測map型態,但有些編譯環境無法使用auto
            if (i.second==most){cout<<i.first;} //first為字典的key, second為字典的value
        }
		cout<<'\n';
    }
    return 0;
}

Python

n = int(input())
for i in range(n):
    s = input()
    dic = {}
    for c in s:
        if not c.isalpha():
            continue
        c = c.lower()
        dic[c] = dic.get(c, 0) + 1
        """
        get()用法:
        取value值

        eg:
        dic.get(c, 0) + 1
        在字典中查找c的值+1,若找不到c就返回0(然後在+1)
        """
    mx = max(dic.values())
    for c in sorted(dic.keys()):
        if dic[c] == mx:
            print(c, end="")
    print()
arrow
arrow
    創作者介紹
    創作者 趴趴熊日常 的頭像
    趴趴熊日常

    資工趴趴熊的小天地

    趴趴熊日常 發表在 痞客邦 留言(0) 人氣()