题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
import java.util.Scanner;
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.hasNextLine()) { // 注意 while 处理多个 case
String s = in.nextLine();
//字符串转字符数组
char[] charArr = s.toCharArray();
Map<Character,Integer> charCountMap = new HashMap<Character,Integer>();
for(char c:charArr){
Integer count = charCountMap.get(c);
if(count==null){
charCountMap.put(c,1);
}else{
charCountMap.put(c,count+1);
}
}
//查找出现次数最少得字符,也可能是多个字符
List<Character> list = new ArrayList<Character>();
Object[] countArrayObj =charCountMap.values().toArray();
Integer[] countArrayInteger = new Integer[countArrayObj.length];
for(int i=0;i<countArrayObj.length;i++){
countArrayInteger[i] = Integer.parseInt(countArrayObj[i].toString());
}
Arrays.sort(countArrayInteger);
int count= countArrayInteger[0];
for(Map.Entry<Character,Integer> entry:charCountMap.entrySet()){
if(count == entry.getValue()){
list.add(entry.getKey());
}
}
//删除出现次数最少得字符
StringBuffer sb = new StringBuffer();
for(char c:charArr){
if(!list.contains(c)){
sb.append(c);
}
}
//输出删除后的字符
System.out.println(sb.toString());
}
}
}
