华为:给定一段英文,长度在100000个字符以内。要求统计出这段文章中,出现最多的英文字母。

版权声明:本博客为记录本人学习过程而开,内容大多从网上学习与整理所得,若侵权请告知! https://blog.csdn.net/Fly_as_tadpole/article/details/82859639

华为2018秋招笔试题:

给定一段英文,长度在100000个字符以内。要求统计出这段文章中,出现最多的英文字母(不理会除英文字母之外的字符,大小写算作同一个字母),以及其出现的次数。本段文章不包含回车换行。如果两个或多个字母出现的次数一样多,那么仅输出排在最前面的一个字母和出现的次数。


1)大小写算作同一个字母:

a-z  ==> 97-122

A-Z  ==> 65-90

将所有的小写字母减32转换为大写字母

2)如果两个或多个字母出现的次数一样多,那么仅输出排在最前面的一个字母和出现的次数。

  ==>我们自然而然的想到了使用关联容器map


#include<iostream>
#include<string>
#include<map>
#include<vector>
#include <algorithm>

using namespace std;
int main()
{
	string str;
	getline(cin,str);
	map<char, int>tmp;
	for (int  i = 0; i < str.length(); ++i)
	{
		if (!(str[i] >= 65 && str[i] <= 90 || str[i] >= 97 && str[i] <= 122))
			continue;
		else
		{
			if (str[i] >= 65 && str[i] <= 90)
				tmp[str[i]]++;
				
			else if (str[i] >= 97 && str[i] <= 122)
			{
				str[i] -= 32;
				tmp[str[i]]++;
			}
		}
	}
	int max = 0;
	for (auto j = tmp.begin(); j != tmp.end(); ++j)
	{
		if (j->second >= max)
			max = j->second;
	}
	auto find_item = find_if(tmp.begin(), tmp.end(),
		[max](const map<char,int>::value_type item)
	{
		return item.second == max;
	});
	char c;	
	c = find_item->first;
	cout <<c<<max<< endl;
	system("pause");
        return 0;
}

猜你喜欢

转载自blog.csdn.net/Fly_as_tadpole/article/details/82859639