题解 | 名字的漂亮度
名字的漂亮度
https://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3
import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int nums = in.nextInt(); in.nextLine(); // 注意 hasNext 和 hasNextLine 的区别 for (int i = 0; i < nums; i++) { int max = 26; int buauty = 0; Map<Character, Integer> map = new TreeMap<>(); String s = in.nextLine(); for (int j = 0; j < s.length(); j++) { if (!map.containsKey(s.charAt(j))) { map.put(s.charAt(j), 1); } else { int count = map.get(s.charAt(j)); count += 1; map.put(s.charAt(j), count); } } Comparator<Map.Entry<Character, Integer>> valCmp = (o1, o2) -> o2.getValue() - o1.getValue(); List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet()); list.sort(valCmp); for (Map.Entry<Character, Integer> characterIntegerEntry : list) { Integer count = characterIntegerEntry.getValue(); buauty += count * max--; } System.out.println(buauty); } } }