【题目19:删除字符串中出现次数最少的字符】

public class Demo19 {
public static void main(String[] args) {

/*
删除字符串中出现次数最少的字符
如果多个字符出现次数一样则都删除

例子:
输入
  abcdd
  字符串中只
 输出
  dd

输入
  aabbccdd

输出
  empty

  如果都被删除  则换为empty

 */
#include<string>
#include<iostream>
#include<map>
#include<algorithm>
#include<vector>
using namespace std;
bool cmp(pair<char, int>& a, pair<char, int>& b)
{
	return a.second < b.second;
}
int main()
{
	string str;
	int tag_cout = 0;
	cin >> str;
	map<char, int>res;
	/*auto Find=tmp.find('c');
	Find->second = 100;
	cout << Find->second;*/
	for (int i = 0; i < str.size(); i++)
	{
		
		if (res.count(str[i])) {
			auto Find = res.find(str[i]);
			Find->second++;
		}
		else {
			res.insert(pair<char, int>(str[i], 1));
		}
	}

	vector<pair<char, int>>tmp(res.begin(), res.end());
	sort(tmp.begin(), tmp.end(), cmp);
	int tag = tmp[0].second;
	for (int i = 0; i < str.size(); ++i)
	{
		auto Find = res.find(str[i]);

		if (Find->second == tag)
		{
			tag_cout++;
			continue;
			
		}
		else {
			cout << str[i] ;
			
		}
	}

	if (tag_cout==str.size())
	{
		cout << "empty";
	}
	return 0;
}

最先开始我想的是用容器内pair对来做,考虑到最后每个字符的统计都是分散的,就pass了;然后自然而然想到了用map。

用map可以修改键值对对应元素的值,但最后的结果输出可能会出现困难(map按照char字符排序,而不是字符的统计个数),就弄了一个容器内pair来排序好,把第一个元素的second作为tag,输出时碰到tag就continue.

思路有了,用哪些工具也一定要想好,推理是否可行,就怕做到半道发现解决不了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值