vector/map-OpenJudge-统计字符数

  • Vector/Map-OpenJudge-统计字符数


  • 题目链接:

6:统计字符数

  • 思路:

在统计单词,字符方面,map有得天独厚的优势,不过有点烦,map的排序是按照key值排的,又没有自定义排序,所以只能用vector把map中所有的pair搬过来排序

  • 代码:

#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
#include<string>
using namespace std;
typedef pair<char, int> p;
bool cmp(p a, p b)
{
	if (a.second < b.second)
		return true;
	else if (a.second > b.second)
		return false;
	else
		return a.first > b.first;
}

int t;

int main()
{
	cin >> t;
	while (t--)
	{
		map<char, int> Words_map;
		vector<p> Words_vec;
		string str;
		int i = 0;
		cin >> str;
		if (str.empty())   //空行忽略
		{
			t++;
			continue;
		}
		while (i!=str.length())
		{
			
			auto it_end = Words_map.end();
			auto it = Words_map.find(str[i]);
			if (it != it_end)
				it->second++;
			else
				Words_map.insert(p(str[i], 1));
			i++;
		}
		for (auto it = Words_map.begin(); it != Words_map.end(); it++)
			Words_vec.push_back(p(it->first, it->second));
		
		sort(Words_vec.begin(), Words_vec.end(), cmp);
		auto it = Words_vec.end();
		it--;
		cout << it->first << " " << it->second << endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值