按外观数量排序 [英] Sort by number of apearances

查看:84
本文介绍了按外观数量排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,给我一个单词,我必须按照该单词出现的次数对它的字母进行排序,如果2个字母出现的次数相同,则将按字典序最小排序。
现在,我开始看一个单词在一个单词中出现了多少次,但是从这里我不知道该怎么做。
这个问题需要我使用BufferedReader和BufferedWriter。

for example, I am given a word and I have to sort its letters by the number of occurrences in that word, if 2 letters appear the same number of times it will be sorted by the lexicographic minimum. For now, I have started to see how many times a letter appears in a word but from here I do not know exactly how to do it. The problem requires me to use BufferedReader and BufferedWriter.

import java.util.*;

public class Main {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Map<Character, Integer> m = new HashMap<>();
    String s = sc.nextLine();
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        if (m.containsKey(c))
            m.put(c, m.get(c) + 1);
        else
            m.put(c, 1);
    }
    for (char letter = 'a'; letter <= 'z'; ++letter)
        if (m.containsKey(letter))
            System.out.println(letter + ": " + m.get(letter));
}

目前,我正在发布单词中最常出现的字母,但是我不知道如何按出现的次数对它们进行排序,并且如果有两个字母以最小的字典顺序出现在相同的次数上。

For the moment I am posting what letters appear most often in the word, but I do not know how to sort them by the number of occurrences and in case there are two letters that appear at the same number of times with the minimum lexicographic.

推荐答案

我希望这就是您想要的

public static void main(String[] args) {
    Map<Character, Integer> m = new HashMap<>();
    String testString = "Instructions";
    Map<Character, List<Character>> map = new HashMap<>();

    for (int i = 0; i < testString.length(); i++) {
        char someChar = testString.charAt(i);
        if (someChar == ' ') {
            continue;
        }
        char ch = testString.charAt(i);
        List<Character> characters = map.getOrDefault(Character.toLowerCase(ch), new ArrayList<>());
        characters.add(ch);
        map.put(Character.toLowerCase(ch), characters);
    }
    List<Map.Entry<Character, List<Character>>> list = new ArrayList<>(map.entrySet());

    list.sort((o1, o2) -> {
        if (o1.getValue().size() == o2.getValue().size()) {
            return o1.getKey() - o2.getKey();/// your lexicographic comparing
        }
        return o2.getValue().size() - o1.getValue().size();
    });

    list.forEach(entry -> entry.getValue().forEach(System.out::print));
}

这篇关于按外观数量排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆