PAT 1042 乙级统计字符串

题目:

请编写程序,找出一段给定文字中出现最频繁的那个英文字母。

输入格式:

输入在一行中给出一个长度不超过 1000 的字符串。字符串由 ASCII 码表中任意可见字符及空格组成,至少包含 1 个英文字母,以回车结束(回车不算在内)。

输出格式:

在一行中输出出现频率最高的那个英文字母及其出现次数,其间以空格分隔。如果有并列,则输出按字母序最小的那个字母。统计时不区分大小写,输出小写字母。

思路:创建一个对应于ascii表的整型数组,通过遍历字符串和字符的ascii值来记录字符的个数,大写字母出现时记录的对应小写字母的位置,最后找出最大值并输出

#include<iostream>
#include<string>
using namespace std;
int main()
{
	int ascii[128] = { 0 };//对应ascii表
	string str;
	char ch = '0';
	while (cin >> str)
	{
		for (int i=0;i<str.size();i++)
		{
			int index = str[i];
			if (index >= 65 && index <= 90)
			{//大写字母ascii值转成小写字母,并记录
				index += 32;
				ascii[index]++;
			}
			else ascii[index]++;
		}
		if (getchar()=='\n')break;
	}
	int maxindex=97,max=ascii[maxindex];
	for (int i = 98; i <=122; i++)
	{//找出最大值
		if (max < ascii[i])
		{
			max = ascii[i];
			maxindex = i;
		}
	}
	ch = maxindex;
	cout << ch << " " << ascii[maxindex];
	return 0;
}

猜你喜欢

转载自www.cnblogs.com/zongji/p/12505691.html
今日推荐