题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
#include <iostream> #include <set> #include <string> using namespace std; int main() { string input; cin >> input; int freq[26] = {0}; // 记录字母出现的频率 for(char c : input) ++freq[c - 'a']; // 寻找出现次数最少的字符 int index = -1; set<char> targetChar; for(int i=0; i<26; ++i) { if(freq[i] == 0) continue; else { if(index == -1) { index = i; targetChar.insert('a' + i); } else if(freq[i] > freq[index]) continue; else if(freq[i] == freq[index]) targetChar.insert('a' + i); else { index = i; targetChar.clear(); targetChar.insert('a' + i); } } } // 删除出现最少的字符targetChar string output; for(int i=0; i<input.size(); ++i) { if(targetChar.count(input[i]) == 0) output.push_back(input[i]); else continue; } cout << output; return 0; }
注意出现最少的字符可能不止一种