题解 | HJ23#删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
char[] chars = str.toCharArray();
//把这些字符以及出现的数目都存进map
Map<Character, Integer> map = new HashMap<>();
for (char c : chars) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
//找到map的value中最小值
Integer min = Collections.min(map.values());
//把map中最小数量的字符存进list
ArrayList<Character> list = new ArrayList<>();
for (int i = 0; i < chars.length; i++) {
if (min.equals(map.get(chars[i]))) {
list.add(chars[i]);
}
}
//若list中不含char中某个字符 则说明数量不是最少 输出它
for (int i = 0; i < chars.length; i++) {
if (!list.contains(chars[i])) {
System.out.print(chars[i]);
}
}
}
}
