题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
#include <iostream>
#include <unordered_map>
#include <unordered_set>
using namespace std;
class Solution {
public:
string removeWords(string s) {
unordered_map<char, size_t> tmap;
for (char ch : s) {
auto it = tmap.find(ch);
if (it != tmap.end()) {
tmap.insert(pair<char, int>(ch, it->second++));
} else {
tmap.insert(pair<char, int>(ch, 1));
}
}
unordered_set<char> tmp;
size_t flag = 0;
for (unordered_map<char, size_t>::iterator it = tmap.begin();
it != tmap.end(); ++it) {
if (it == tmap.begin()) {
flag = it->second;
tmp.insert(it->first);
continue;
}
if (flag > it->second) {
tmp.clear();
tmp.insert(it->first);
flag = it->second;
} else if (flag == it->second) {
tmp.insert(it->first);
}
}
tmap.clear();
string ret;
for (char ch : s) {
// 没有找到
if (tmp.find(ch) == tmp.end()) {
ret.push_back(ch);
}
}
tmp.clear();
return ret;
}
};
int main() {
Solution s;
string a;
while (cin >> a) { // 注意 while 处理多个 case
cout << s.removeWords(a) << endl;
}
}
// 64 位输出请用 printf("%lld")

查看9道真题和解析