根据出现次数排列字符串的字符,如果元素不重复,则保持插入顺序

输入

你好世界

输出

低头

我找到了一些计算出现次数的方法的答案,但这些方法弄乱了插入顺序,为了得到上述输出而需要维护。我正在寻找如何解决它的方法。我不擅长 Java 8 流和地图!!!虽然会尝试理解。


LEATH
浏览 93回答 2
2回答

江户川乱折腾

Map适合根据出现次数获取字符的情况。Map只是将数据存储在键值对中的结构。有关详细信息,请参见此处。因此,要获取字符及其在没有 java8 的情况下出现的次数,您可以这样做:public Map<Character, Long> countChar(String string) {&nbsp; &nbsp; Map<Character, Long> result = new LinkedHashMap<>();&nbsp; &nbsp; char[] chars = string.toCharArray();&nbsp; &nbsp; for (char c : chars) {&nbsp; &nbsp; &nbsp; &nbsp; if (result.get(c) != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.put(c, result.get(c) + 1);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.put(c, 1L);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}接下来,您要按出现次数对值进行排序。在这种情况下,您可以按值对结果映射进行排序。请参阅Sort a Map<Key, Value> by values以找到您更熟悉的解决方案。要在没有流的情况下执行此操作,但使用 java8:List<Map.Entry<Character, Long>> list = new ArrayList<>(result.entrySet());list.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));现在您可以像这样打印每个字符:StringBuilder output = new StringBuilder();for (Map.Entry<Character, Long> entry : list) {&nbsp; &nbsp; output.append(entry.getKey());}System.out.println(output);

青春有我

一种可能的解决方案可能是以下方法:private static String rearrange(String text) {&nbsp; &nbsp; return Arrays.stream(text.split("")) // create a stream with all letters&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) // create a map counting the occurrences of each letter&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .entrySet().stream() // create a stream of the map&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .sorted(Map.Entry.<String, Long>comparingByValue().reversed() // sort the letters by frequency, reversed for most frequent first&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .thenComparingInt(e -> text.indexOf(e.getKey()))) // sort by position in original text if letter frequency is equal&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(Map.Entry::getKey) // map back to stream with all letters&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.joining()); // join all letters}它返回重新排列的字符串:String text = "HelloWorld";String rearranged = rearrange(text);System.out.println(rearranged);哪个打印:loHeWrd
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java