题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next();
char[] chars = str.toCharArray();
HashMap<Character, Integer> map = new HashMap();
// 记录每个字符的出现次数
for (char c : chars) {
map.merge(c, 1, Integer::sum);
/* if (map.get(c) == null) {
map.put(c,1);
} else {
map.put(c,map.get(c) + 1);
}*/
}
// 统计出最小的次数
Collection<Integer> values = map.values();
Integer min = Collections.min(values);
Integer max = Collections.max(values);
String res = str; // 保存最终结果
if (!min.equals(max)) { // 边界条件 ab -> ab abccc -> ccc
// 遍历map集合
Set<Map.Entry<Character, Integer>> entries = map.entrySet();
for (Map.Entry<Character, Integer> entry : entries) {
if (entry.getValue().equals(min)) {
res = res.replaceAll(String.valueOf(entry.getKey()), "");
}
}
}
System.out.println(res);
in.close();
}
}
