题解 | #删除字符串中出现次数最少的字符#

删除字符串中出现次数最少的字符

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);
        }
    }
}

全部评论

相关推荐

程序员鼠鼠_春招版:我要12k吧我挂了,还招呢,天天被割,这点钱都不舍得出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务