题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
import java.util.*;
import java.util.regex.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
// 注意:map实现Comparator只能实现对key的排序
// TreeMap<String,Integer> tm = new TreeMap<String,Integer>(new Comparator<String>(){
// public int compare(String a , String b){
// return a.compareTo(b);
// }
// });
// 对values排序需要通过Entry整体化转为List,然后实现Comparator通过getvalues获取values排序
// 正则中{}是匹配的次数,有边界和指定次数
// 而[] 是从中选一个
// () 是指一个整体
TreeMap<String,Integer> tm = new TreeMap<String,Integer>();
for(int i = 0 ; i < str.length(); i++){
String str_=str.substring(i,i+1);
if(!tm.containsKey(str_)){
tm.put(str_,1);
}else{
tm.put(str_,tm.get(str_)+1);
}
}
ArrayList<Map.Entry<String,Integer>> arr = new ArrayList<Map.Entry<String,Integer>>(tm.entrySet());
Collections.sort(arr,new Comparator<Map.Entry<String,Integer>>(){
public int compare(Map.Entry<String,Integer> a,Map.Entry<String,Integer> b){
return a.getValue()-b.getValue();
}
});
Integer less = arr.get(0).getValue();
String reg = "" ;
for(Map.Entry<String,Integer> e:arr){
if(e.getValue()==less){
reg+=e.getKey();
}else{
break;
}
}
reg = "[" + reg + "]" ;
String str_ = Pattern.compile(reg).matcher(str).replaceAll("");
System.out.print(str_);
}
}