题解 | #删除字符串中出现次数最少的字符#优雅解法
删除字符串中出现次数最少的字符
http://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
优雅解法,使用replaceAll("a","")计算出目标字符出现的次数
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* @author saint
* @date 2022/6/2
* @info 删除出现次数最少的字符;优雅永不过时
**/
public class Main {
//解题思路:分步完成,第一步记录每个字符出现的次数以及找到最小出现次数,第二步替换目标字符为空格
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int minCount = str.length();
int count = 0;
Map<Character,Integer> map = new HashMap<>();
char[] arr = str.toCharArray();
if(arr.length > 0){
for(int i=0; i<arr.length; i++){
char c = arr[i];
if(!map.containsKey(c)){
count = str.length() - str.replaceAll(c+"","").length();
map.put(c,count);
if(count <= minCount){
minCount = count;
}
}
}
if(map.keySet().size() > 0){
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
Character k = entry.getKey();
Integer v = entry.getValue();
if (v.equals(minCount)) {
str = str.replaceAll(k.toString(), "");
}
}
}
System.out.println(str);
}
}
}