NowCode:HJ23 删除字符串中出现次数最少的字符

题目: 删除字符串中出现次数最少的字符

对于给定的仅由小写字母构成的字符串,删除字符串中出现次数最少的字符。输出删除后的字符串,字符串中其它字符保持原来的顺序。
特别地,若有多个字符出现的次数都最少,则把这些字符都删除。

输入描述:

在一行上输入一个长度为 1≦length(s)≦201≦length(s)≦20 ,仅由小写字母构成的字符串 ss ,代表待处理的字符串。

输出描述:

在一行上输出一个字符串,代表删除后的答案。保证这个字符串至少包含一个字符。

示例1

1
2
3
4
5
6
7
8
输入:
aabcddd

输出:
aaddd

说明:
在这个样例中,出现次数最少的字符为 ‘b’ 和 ‘c’,因此需要同时删除这两个字符。

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <climits>
#include <iostream>
#include <string>
#include <map>
#include <utility>
using namespace std;

int main() {
std::string s;
getline(cin, s);
std::map<char, int> words;
for (char& ch : s) {
auto result = words.insert(std::pair<char, int>(ch, 1));
if (!result.second) {
result.first->second += 1;
}
}
int minValue = INT_MAX;
for (auto it = words.begin(); it != words.end(); it++) {
if (it->second < minValue) {
minValue = it->second;
}
}
std::string targetStr;
for (auto it = words.begin(); it != words.end(); it++) {
if (it->second == minValue) {
targetStr += it->first;
}
}
std::string outStr;
for (char& ch : s) {
if (targetStr.find(ch) == std::string::npos) {
outStr += ch;
}
}
cout << outStr << endl;
}

思路

我选择用map 的键值对记录每个字符的出现次数,

然后遍历map,找到出现次数最少的次数是多少

再次遍历map,找到最少的次数对应的字符(可能是一个,可能是多个)

判断输入字符串中字符,如果字符不是出现次数最少的,则加到outStr字符串中

最后输出outStr字符串