题解 | #名字的漂亮度#
贪心算法,将名字中出现的字母按照频率排序,频率越高的权重越高。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
for (int i = 0; i < n; i++) {
String name = sc.nextLine();
System.out.println(getBeautyDegree(name));
}
}
public static int getBeautyDegree(String name) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
List<Map.Entry<Character, Integer>> listMapEntry = new ArrayList<>(map.entrySet());
listMapEntry.sort((o1, o2) -> -(o1.getValue() - o2.getValue()));
int startScore = 26, degree = 0;
for (Map.Entry<Character, Integer> entry : listMapEntry) {
degree += startScore * entry.getValue();
startScore--;
}
return degree;
}
}
查看23道真题和解析