题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String s = in.nextLine(); Map<Character, Integer> map = new HashMap<>(); for(char c : s.toCharArray()){ map.put(c, map.getOrDefault(c, 0) + 1); } //根据value值排序 List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>(){ @Override public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2){ return o2.getValue() - o1.getValue() ; } }); List<Character> list2 = new ArrayList<>(); int size = list.size(); for(int i = 0; i < size; i++){ Map.Entry<Character, Integer> tempMap = list.get(i); list2.add(tempMap.getKey()); while(i + 1 < size && list.get(i + 1).getValue() == tempMap.getValue()){ list2.add(list.get(i + 1).getKey()); i++; } //对list2排序输出 Collections.sort(list2); for(char c : list2){ System.out.print(c); } list2.clear(); } System.out.println(); } } }