PAT乙级1042

一世执手 提交于 2019-11-26 20:30:04

题目链接

https://pintia.cn/problem-sets/994805260223102976/problems/994805280817135616

题解

用数组count存储字母出现次数,数组下标代表字母,数组元素是次数。遍历字符串,统计各字母出现次数,最后遍历count寻找出现次数最多的字母。

// PAT BasicLevel 1042
// https://pintia.cn/problem-sets/994805260223102976/problems/994805280817135616

#include <iostream>
#include <string>
using namespace std;

int main()
{
    // 26个字母计数
    int count[26];
    fill(count,count+26,0);

    // 获取字符串
    string str;
    getline(cin, str);  // 字符串可能包含空格

    // 统计字符出现次数
    for(int i=0;i<str.length();++i){
        if(isalpha(str[i])){
            count[tolower(str[i])-'a']++;
        }
    }

    // 寻找出现最频繁的英文字母(其实可以在统计的时候进行)
    int maxCount=-1;
    int maxIndex=0;
    for(int i=0;i<26;++i){
        if(count[i]>maxCount){  // 用于实现数量并列则输出字母序最小的那个字母
            maxCount = count[i];
            maxIndex = i;
        }
    }

    // 输出结果
    cout << char('a' + maxIndex)<< ' ' << maxCount;

    //system("pause");
    return 0;
}

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!