题解 | #名字的漂亮度#
名字的漂亮度
https://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3
核心思想:
1.先把每个字符出现的次数统计出来
2.将出现次数从大到小排序
3.从26漂亮度开始倒退乘以 前面的排序
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); for (int j = 0; j < n; j++) { String string = in.next(); // 统一转成小写 char[] charArray = string.toLowerCase().toCharArray(); // 每个字符和对应的出现次数 HashMap<Character, Integer> hashMap = new HashMap<>(); for (int i = 0; i < charArray.length; i++) { int count = 1; if (hashMap.get(charArray[i]) != null){ continue; } for (int k = i + 1; k < charArray.length; k++) { if (charArray[i] == charArray[k]) { count++; } } hashMap.putIfAbsent(charArray[i], count); } ArrayList<Integer> countList = new ArrayList<>(); Iterator<Map.Entry<Character, Integer>> iterator = hashMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Character, Integer> entry = iterator.next(); countList.add(entry.getValue()); } // 根据出现次数降序排 Collections.sort(countList, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); // 最大漂亮程度 = 出现次数 * 最大漂亮度 int good = 0; // 从26最大往小 int max = 26; for (Integer count : countList) { // 漂亮度 = 每个字符的漂亮度 之和 good = good + (max * count); max--; } System.out.println(good); } } }