将单词的字母排序[关闭]

问题描述 投票:-1回答:1
我有问题。一个单词以英文字母的小写字母给出。显示单词中出现的所有字母,重新排列,以便最开头出现的字母出现。如果字母出现的次数相同,则小写字母将在字母排序后首先显示。Java中某些类和操作很慢。因此,建议使用BufferedReader和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)); } }

java hashmap bufferedreader bufferedwriter
1个回答
0
投票
这基于您已经创建的地图。

有几种方法可以做到这一点。两者的想法都是先根据字母的数量对地图的条目进行排序,然后再根据字母本身的数量进行排序。

计数以相反的顺序排序,字母以正常的词汇顺序排序。

// sort the entries based first on count and then on lexical order. // create an array of entries with which to work Entry<Character, Integer>[] entries = m.entrySet() .toArray(Entry[]::new); for (int i = 0; i < entries.length - 1; i++) { for (int k = i + 1; k < entries.length; k++) { // sort values based on count in descending order // the valcomp should be < 1 for reverse compare // as the entry k is compared to entry i int valcomp = entries[k].getValue() .compareTo(entries[i].getValue()); // sort keys based on ascending lexical order // the keycomp should also be < 1 for normal compare int keycomp = entries[i].getKey() .compareTo(entries[k].getKey()); // if the desired conditions aren't met, swap the entries if (!(valcomp < 1 && keycomp < 1)) { Entry<Character, Integer> temp = entries[i]; entries[i] = entries[k]; entries[k] = temp; } } } // now simply build up the string result String result = ""; for (Entry<Character, Integer> e : entries) { result += (e.getKey() + "") .repeat(e.getValue()); } System.out.println(result);

另一种方法是使用流。排序和合并方法全部组合为一个操作。

String result2 = m.entrySet().stream() // sort the entries as required .sorted(Comparator.comparing( Entry<Character, Integer>::getValue, Comparator.reverseOrder()) .thenComparing( Entry<Character, Integer>::getKey)) // convert the entries to individual strings .map(e -> (e.getKey() + "") .repeat(e.getValue())) // concatenate the strings .reduce("", (res, str) -> res + str); System.out.println(result2);

© www.soinside.com 2019 - 2024. All rights reserved.