题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
这应该是最简洁的代码了。首先将字符串转为char数组加入TreeMap,得到按ASCII从小到大排好序的结果。然后再将map.entry放入List,再按value值从大到小顺序排一次序即可得到结果。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
char[] ch = in.nextLine().toCharArray();
TreeMap<Character, Integer> map = new TreeMap<>();
for(char c:ch)map.put(c,map.getOrDefault(c,0)+1);
List<Map.Entry> list=new ArrayList<>(map.entrySet());
list.sort((o1,o2)->(int)o2.getValue()-(int)o1.getValue());
for(Map.Entry en:list)System.out.print(en.getKey());
}
}
}

