题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
做的有点麻烦,用hashmap 存储每个字符出现的次数。然后对map里的value进行排序,找到最小值。最后遍历map,找到value是最小值的key,替换为空。
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String str = in.next();
HashMap<String, Integer> map = new HashMap<>();
for(int i=0; i<str.length(); i++){
if(!map.keySet().contains(str.charAt(i)+"")){
map.put(str.charAt(i)+"", 0);
}else{
map.put(str.charAt(i)+"", map.get(str.charAt(i)+"")+1);
}
}
Collection c = map.values();
Object[] i = c.toArray();
Arrays.sort(i);
int min = (int)i[0];
for(String s:map.keySet()){
if(map.get(s) == min){
str = str.replace(s, "");
}
}
System.out.print(str);
}
}
}
牛客公司氛围 254人发布
查看21道真题和解析