题解 | #字符统计#
字符统计
http://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
这道题目的核心地方时学会java中对HashMap进行排序。
将HashMap中Entry元素放入List中
对List使用Collections.sort()方法进行排序,并且重写comparator方法
输出排序后的List结果
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String line = sc.nextLine().trim(); HashMap<Character,Integer> hm = new HashMap<>(); for (int i = 0; i < line.length(); i++) { if(hm.containsKey(line.charAt(i))){ hm.put(line.charAt(i),hm.get(line.charAt(i))+1); }else { hm.put(line.charAt(i),1); } } LinkedList<Map.Entry<Character,Integer>> list = new LinkedList<>(hm.entrySet()); Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() { @Override public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) { if(o1.getValue()== o2.getValue()){ return o1.getKey().compareTo(o2.getKey()); }else { return o2.getValue()-o1.getValue(); } } }); StringBuffer sb = new StringBuffer(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i).getKey()); } System.out.println(sb.toString()); } } }