PAT乙级1042

时间:2019-08-10
本文章向大家介绍PAT乙级1042,主要包括PAT乙级1042使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目链接

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/

欢迎讨论和交流!


原文地址:https://www.cnblogs.com/chouxianyu/p/11332757.html