机试 -- 字符个数统计与筛选

题目

时间限制 C/C++ 3s 其他 6s, 空间限制 C/C++ 32768k 其他 65535k

题目描述
给定一个长度不限的字符串,请找出该字符串中出现次数最多的那个字符,并打印出该字符及其出现次数; 如果多个字符的出 现次数相同,只打印首个字符;输出字符的大小写格式要与输 入保持一致,大小写不敏感模式下, 输出字符的大小写格式与该> 字符首次出现时的大小写格式一致。实现时无需考虑非法输入。

输入描述
输入为 字符串大小写敏感标记 其中”大小写敏感标记”为可选参数,取值范围为true|false,true表示大小写敏感;缺省取值true
例子: abcdabcde false

输出描述
输出:字符出现次数 如果出现次数最多的字符有多个,输出字典序最小的那个字 符。输出的字符都为小写字符
例子: a 2

解题思路

1、大小写敏感时
用一个数组int arr_count[52] = {0};来表示‘A-Za-z’52个字符每个字符在字符串中出现的次数。然后遍历数组,找到最大值,及最大值的索引(从而找出最大数目的字符)

2、大小写不敏感时

char buf[26] = {0}; //记录 a-z A-Z 26个大小写不敏感字符中,最先出现的是大写字符还是小写字符
bool isAppear[26] = {false}; //字符是否出现过,如果出现了则不再写入buf
int count[26] = {0};//每个字符的数量

然后遍历数组,找到最大值,及最大值的索引(从而找出最大数目的字符)

参考答案

#include <iostream>

using namespace std;

int main()
{    
    string str_Source;
    string str_sen;

    cin >> str_Source;
    cin >> str_sen;

    if (str_sen == "false") //大小写不敏感
    {
        bool isAppear[26] = {false}; //出现过
        char buf[26] = {0};
        int count[26] = {0};
        for (unsigned int i = 0; i < str_Source.length(); ++i)
        {
            if (str_Source.at(i) >= 'a') //小写
            {
                if (!isAppear[str_Source.at(i) - 'a']) //没出现过
                    buf[str_Source.at(i) - 'a'] = str_Source.at(i);
                isAppear[str_Source.at(i) - 'a'] = true;
                count[str_Source.at(i) - 'a']++;
            }
            else //大写
            {
                if (!isAppear[str_Source.at(i) - 'A']) //没出现过
                    buf[str_Source.at(i) - 'A'] = str_Source.at(i);
                isAppear[str_Source.at(i) - 'A'] = true;
                count[str_Source.at(i) - 'A']++;
            }
        }

        int index = 0, max = 0;
        for (int i = 25; i >= 0; -- i)
        {
            if (count[i] > max)
            {
                max = count[i];
                index = i;
            }
        }
        cout << buf[index] << " " << count[index] << endl;
    }
    else //缺省参数为true
    {
        int arr_count[52] = {0}; //52个字符的个数
        for (unsigned int i = 0; i < str_Source.length(); ++i)
        {
            arr_count[str_Source.at(i) - 'A'] ++;
        }

        int index = 0, max = 0;
        for (int i = 51; i >= 0; -- i)
        {
            if (arr_count[i] > max)
            {
                max = arr_count[i];
                index = i;
            }
        }
        cout << char(index + 'A') << " " << arr_count[index] << endl;
    }

    return 0;
}

说明

本答案没有经过全面验证,可能存在一些问题。欢迎反馈:[email protected]

猜你喜欢

转载自blog.csdn.net/baidu_33850454/article/details/81783095
今日推荐