题解 | #字符统计#
字符统计
http://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
思路:
1.用map统计各个字符出现次数
2.把map放入ArrayList集合中。
3.利用Collections.sort()方法对list中的map进行排序。
4.打印list中entry的key。打印完一组记得换行。
public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String str=in.next(); HashMap<Character,Integer> map=new HashMap<>(); for(int i=0;i<str.length();i++){ map.put(str.charAt(i),map.getOrDefault(str.charAt(i),0)+1);//统计字符出现次数 } ArrayList<Map.Entry> list=new ArrayList<>(map.entrySet());//把map放入list中。 Collections.sort(list, new Comparator<Map.Entry>() { @Override public int compare(Map.Entry o1, Map.Entry o2) { if(o1.getValue()!=o2.getValue()){//若次数不同 return (int)(o2.getValue())-(int)(o1.getValue());//一定记得转换类型,否则报错Object不能使用'-'运算符。 }else{//若次数相同 return (char)(o1.getKey())-(char)(o2.getKey()); } } }); //打印key for (Map.Entry entry : list) { System.out.print(entry.getKey()); } System.out.println();//打印完一组换行 } }