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.
思路有了,用哪些工具也一定要想好,推理是否可行,就怕做到半道发现解决不了!