题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public String deleteLeast(String str)
{
Set<Character> set=new HashSet<>();
//只有小写字母,用数组模拟哈希表,对应索引的值代表字母出现的次数
int[] hash=new int[26];
Arrays.fill(hash,Integer.MAX_VALUE);
for (int i=0;i<str.length();i++)
{
int temp=str.charAt(i)-'a';
if (hash[temp]==Integer.MAX_VALUE) hash[temp]=0;
hash[temp]++;
}
//找到最小出现次数,两次遍历记录所有最小次数出现的字符
int min=Integer.MAX_VALUE;
for (int i=0;i<26;i++)
{
if (hash[i]<min) min=hash[i];
}
for (int i=0;i<26;i++)
{
if (hash[i]==min) set.add((char)(i+'a'));
}
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);
}
}
}
