题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
1.将字符及其出现次数存入map,遍历map获取出现最少的字符次数; 2.遍历map根据出现次数等于最少出现次数条件操作,组装最终输出结果;
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; public class StrOperate_del_HJ23 { public static void main(String[] args) throws Exception{ BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); String line = null; while((line = read.readLine()) != null){ HashMap<Character,Integer> temp =new HashMap<>(); char [] input=line.toCharArray(); for(char s:input){ String lastLine=line.replaceAll(String.valueOf(s),""); temp.put(s,line.length()-lastLine.length()); } //快速找出最小值 int min = Integer.MAX_VALUE; for (int times:temp.values()){ min = Math.min(min,times); } //组织输出结果 String outputStr = line; for (HashMap.Entry<Character,Integer> entry : temp.entrySet()){ String minChar = String.valueOf(entry.getKey()); int mintimes = entry.getValue(); if(mintimes==min){ outputStr=outputStr.replaceAll(minChar,""); } } System.out.println(outputStr); } } }