HJ23题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
#include <iostream> #include <map> #include <vector> #include <algorithm> using namespace std; int main() { string input; cin >> input; map<char, int> mp; for (int i = 0; i < input.size(); i++) { // 利用map存储不同字符的出现次数 auto it = mp.insert(pair<char, int>(input[i], 1)); if (it.second == false) { it.first->second += 1; } } vector<char> chs; int count = 20; for (auto it = mp.begin(); it != mp.end(); it++) { // 找到最少的次数 if (it->second < count) { count = it->second; } } for (auto it = mp.begin(); it != mp.end(); it++) { // 找到最小次数对应的字符->放到vector中 if (it->second == count) { chs.push_back(it->first); } } for (int i = 0; i < input.size(); i++) { if (find(chs.begin(), chs.end(), input[i]) != chs.end()) { // 移除string中 最小次数对应的字符 input = input.erase(i, 1); i--; } } cout << input; }#刷题记录#