题解HJ23 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String s = in.nextLine();
String[] split = s.split("");
List<String> list = Arrays.asList(split);
Map<String, Long> map = list.stream().collect(Collectors.groupingBy(x -> x,
Collectors.counting()));
//拿到最小value
Long min = 20L;
for (Map.Entry<String, Long> entry : map.entrySet()) {
if (entry.getValue().compareTo(min) < 0)
min = entry.getValue();
}
//拿到对应的键
List<String> arr = new ArrayList();
for (Map.Entry<String, Long> entry : map.entrySet()) {
if (min.equals(entry.getValue()))
arr.add(entry.getKey());
}
for (int i = 0; i < arr.size(); i++) {
s = s.replace(arr.get(i), "");
}
System.out.println(s);
}
}
}
最笨的办法
查看26道真题和解析