题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include <set>
#include <algorithm>
#include <map>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::set;
using std::map;
using std::sort;
void process_string(string& str) {
// 将所有字符转换为小写
for (auto& ch : str) {
ch = tolower(ch);
}
//// 打印转换后的字符串
//for (auto ch : str) {
// cout << ch << " ";
//}
//cout << endl;
// 使用 set 来存储唯一字符
set<char> uniqueChars;
// 使用 map 来统计每个字符出现的次数
map<char, int> charCount;
// 遍历字符串
for (auto it = str.begin(); it != str.end(); it++) {
uniqueChars.insert(*it);
charCount[*it]++;
}
// 创建数组来存储出现次数
int arr[20] = { 0 };
int i = 0;
// 将出现次数复制到数组中
for (auto& elem : charCount) {
arr[i++] = elem.second;
}
// 对数组进行排序
sort(arr, arr + i);
// 输出出现次数最少的字符,并从原始字符串中删除这些字符
/*cout << "Least frequent character(s): ";*/
for (auto& elem : charCount) {
if (elem.second == arr[0]) {
/* cout << "'" << elem.first << "' ";*/
while (true) {
size_t pos = str.find(elem.first);
if (pos ==
string::npos) { //检查返回的位置是否等于 std::string::npos 来判断是否找到了子串。
break;
}
str.erase(pos, 1);//删除str pos位置的一个字符
}
}
}
//cout << endl;
cout << str << endl;
}
int main() {
string str;
getline(cin, str);
process_string(str);
return 0;
}
查看20道真题和解析