题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>
using namespace std;
string deleteLeastFreqChar(string str) {
unordered_map<char, int> charFreqMap; // 哈希表记录每个字符出现的次数
for (char c : str) {
charFreqMap[c]++;
}
int leastFreq = str.size(); // 最少出现次数的字符的出现次数
for (auto p : charFreqMap) {
leastFreq = min(leastFreq, p.second); // 找到最少出现次数的字符的出现次数
}
string result;
for (char c : str) {
if (charFreqMap[c] == leastFreq) { // 如果当前字符的出现次数是最少出现次数
continue; // 则跳过当前字符,不加入结果字符串中
} else {
result =result + c; // 否则加入结果字符串中
}
}
return result;
}
int main() {
string str;
getline(cin, str); // 输入字符串
string result = deleteLeastFreqChar(str); // 删除出现次数最少的字符
cout << result << endl; // 输出删除后的字符串
return 0;
}



