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

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

https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9

做的有点麻烦,用hashmap 存储每个字符出现的次数。然后对map里的value进行排序,找到最小值。最后遍历map,找到value是最小值的key,替换为空。

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.hasNext()) { // 注意 while 处理多个 case
            String str = in.next();
            HashMap<String, Integer> map = new HashMap<>();
            for(int i=0; i<str.length(); i++){
                if(!map.keySet().contains(str.charAt(i)+"")){
                    map.put(str.charAt(i)+"", 0);
                }else{
                    map.put(str.charAt(i)+"", map.get(str.charAt(i)+"")+1);
                }
            }
            Collection c = map.values();
            Object[] i = c.toArray();
            Arrays.sort(i);
            int min = (int)i[0];
            for(String s:map.keySet()){
                if(map.get(s) == min){
                    str = str.replace(s, "");
                }
            }
            System.out.print(str);
        }
    }
}

全部评论

相关推荐

Sigma429:极兔啊,薪资开的巨低,还在上海,索性不做笔试了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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