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

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

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

import java.util.*;

public class Main {

    public static void main(String [] args) {
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNext()) {

            String next = scanner.next();
            char[] chars = next.toCharArray();
            HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
            for (char aChar : chars) {
                if(stringIntegerHashMap.containsKey(String.valueOf(aChar))){
                    stringIntegerHashMap.put(String.valueOf(aChar),stringIntegerHashMap.get(String.valueOf(aChar))+1);

                }else {
                    stringIntegerHashMap.put(String.valueOf(aChar),1);

                }


            }
            //System.out.println(stringIntegerHashMap.toString());
            Set<Map.Entry<String, Integer>> entries = stringIntegerHashMap.entrySet();
            ArrayList<Map.Entry<String, Integer>> entries1 = new ArrayList<>(entries);

            Collections.sort(entries1,(o,p)->{
                return o.getValue()-p.getValue();
            });
            LinkedHashMap<String, Integer> stringIntegerLinkedHashMap = new LinkedHashMap<>();

            for (Map.Entry<String, Integer> stringIntegerEntry : entries1) {
                stringIntegerLinkedHashMap.put(stringIntegerEntry.getKey(),stringIntegerEntry.getValue());

            }
            //System.out.println(stringIntegerLinkedHashMap.toString());
            Set<Map.Entry<String, Integer>> entries2 = stringIntegerLinkedHashMap.entrySet();
            int min=0;

            for (Map.Entry<String, Integer> stringIntegerEntry : entries2) {
                min=stringIntegerEntry.getValue();
                break;


            }
            for (Map.Entry<String, Integer> stringIntegerEntry : entries2) {
                if(stringIntegerEntry.getValue()==min){
                    next = next.replaceAll(stringIntegerEntry.getKey(), "");


                }


            }
            System.out.println(next);


        }}
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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