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

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

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

全部评论

相关推荐

不愿透露姓名的神秘牛友
12-17 17:40
点赞 评论 收藏
分享
程序员花海_:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务