题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public String deleteLeast(String str)
{
//键值对分别代表字符及其出现的次数
Map<Character,Integer> map=new HashMap<>();
//记录需要被删除的字符
Set<Character> set=new HashSet<>();
for (int i=0;i<str.length();i++)
{
char temp=str.charAt(i);
map.put(temp,map.getOrDefault(temp,0)+1);
}
//将Entry对象根据其出现次数进行比较构造一个小顶堆
PriorityQueue<Map.Entry<Character,Integer>> priorityQueue=new PriorityQueue<>((o1,o2)->{
return o1.getValue()-o2.getValue();
});
for (Map.Entry<Character,Integer> entry:map.entrySet())
{
priorityQueue.offer(entry);
}
//找到小顶堆中最小出现次数及其字符将其添加到哈希表中
Map.Entry<Character,Integer> leastentry=priorityQueue.poll();
set.add(leastentry.getKey());
int minTimes=leastentry.getValue();
//遍历小顶堆,如果其出现次数和最小相同,则将其添加到hashSet中
while (!priorityQueue.isEmpty())
{
if (priorityQueue.peek().getValue()==minTimes)
{
set.add(priorityQueue.peek().getKey());
priorityQueue.poll();
}else break;
}
//通过stringBuilder对象添加不需要被删除的字符并返回结果
StringBuilder sb=new StringBuilder();
for (int i=0;i<str.length();i++)
{
char temp=str.charAt(i);
if (!set.contains(temp))
{
sb.append(temp);
}
}
return sb.toString();
}
public static void main(String[] args) {
Main main=new Main();
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String a = in.next();
String res=main.deleteLeast(a);
System.out.println(res);
}
}
}