我正在尝试对字符列表进行排序,并按频率顺序及其相关频率输出它们。例如,如果用户输入“beeeerr”,我希望它输出“e freq:4,r freq:2,b freq:1”
这是我到目前为止所拥有的:
public static void sort(String charInput) {
int frequency = 0;
char [] charArray = charInput.toCharArray();
for (char charValue = ' '; charValue <= '~'; charValue++) {
frequency = 0;
for (int i = 0; i < charInput.length(); i++) {
char compare = charArray[i];
//charInput.charAt(i)
if (compare == charValue) {
frequency += 1;
}
}
if (frequency > 0) {
System.out.println(charValue + " freq: " + frequency);
}
}
}
这个问题是它按字母顺序输出频率。我无法弄清楚如何按其频率对输出进行排序。我知道如何使用Hashmaps或Arraylists轻松完成此操作,但我不允许使用它们。任何帮助将不胜感激
答案 0 :(得分:0)
//128 is for ascii, change it to 256 for extended ascii
//I assume all characters in the input are in ascii or extended ascii
public void frequencySort(String s) {
int n = s.length();
List<Character>[]res = new ArrayList[n+1];
int []cnt = new int[128];
char []ss = s.toCharArray();
for(int i=0;i<n;++i){
res[i+1]=new ArrayList<>();
cnt[ss[i]]++;
}
for(int i=0;i<128;++i){
if(cnt[i]!=0){
res[cnt[i]].add((char)i);
}
}
for(int i=n;i>0;--i){
if(!res[i].isEmpty()){
for(char c:res[i])
System.out.println("input has "+i+" " +c);
}
}
}
input has 4 e
input has 2 r
input has 1 b
答案 1 :(得分:0)
使用Java 8 Stream API,您通常可以使用一个内容执行此类操作:
str.chars().mapToObj(e->(char)e).collect(Collectors.toSet()).stream()
.collect(Collectors.toMap(ch -> ch, ch -> str.length() - str.replaceAll(ch.toString(), "").length()))
.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.forEach(e -> System.out.println(e.getKey() + " freq: " + e.getValue()));