gpt4 book ai didi

java - 对单词字符进行排序的问题

转载 作者:行者123 更新时间:2023-12-01 18:11:14 26 4
gpt4 key购买 nike

我有一个问题,我已经困扰了一段时间了。给定一个由英文字母的小写字母或大写字母组成的单词,对这些字符进行排序,以便在该单词中最常出现的字符出现在第一个位置,如果它们出现的次数相同,那么它们将按字典顺序排序。如:

input: Instructions

output: iinnssttcoru

到目前为止我已经写了这篇文章,但从这里我不知道如何对它们进行排序并正确显示,有什么提示吗?

public class Main {
public static void main(String[] args) throws IOException {
String testString = " ";
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
testString = rd.readLine();
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());}

最佳答案

您可以添加TreeMap counterAppear,其中key是字符的重复次数,value是具有相同字符的列表key 重复次数。该 list 在打印前需要进行排序,以确保顺序符合要求。使用 TreeMap 确保 map 按键(重复次数)排序。

public static void main(String[] args) throws IOException {
String testString = " ";
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
testString = rd.readLine();
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);
//Change to Optimize Code
Character keyCharacter = Character.toLowerCase(ch);
if (map.get(keyCharacter) == null) {
map.put(keyCharacter, new ArrayList<>());
}
List<Character> characters = map.get(keyCharacter);
characters.add(ch);
}
TreeMap<Integer, List<Character>> counterAppear = new TreeMap<>();
for (Map.Entry<Character, List<Character>> entry : map.entrySet()) {
Character character = entry.getKey();
int repeatCharTime = entry.getValue().size();
if (counterAppear.get(repeatCharTime) == null) {
counterAppear.put(repeatCharTime, new ArrayList<>());
}
List<Character> characters = counterAppear.get(repeatCharTime);
characters.add(character);
}

for (Integer repeatCharTime : counterAppear.descendingKeySet()) {
List<Character> keyCharacters = counterAppear.get(repeatCharTime);
Collections.sort(keyCharacters);
for (Character character : keyCharacters) {
for (int i = 0; i < repeatCharTime; i++) {
System.err.print(character);
}
}
}
}

关于java - 对单词字符进行排序的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60466208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com