题解 | #名字的漂亮度#
名字的漂亮度
https://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3
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.hasNextInt()) { // 注意 while 处理多个 case
int n = in.nextInt();
in.nextLine();
for(int i = 0; i < n; i++){
// int beauty = getBeauty(in.nextLine());
System.out.println(getBeauty(in.nextLine()));
}
}
}
private static int getBeauty(String s){
Map<Character, Integer> map = new HashMap<Character, Integer>();
for(char c :s.toCharArray()){
c = Character.toLowerCase(c);
map.put(c, map.getOrDefault(c,0) + 1);
}
//将map放入List中,根据value值排序
List<Map.Entry<Character,Integer>> entryList = new ArrayList<>(map.entrySet());
//排序
Collections.sort(entryList, 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();
}
});
//排好序后,需要使用LinkedHashMap<Character, Integer> 来保准数据, 不过这里只需要保存value的值即可
int sum = 0;
int beauty = 26;
for(Map.Entry<Character, Integer> m : entryList){
sum += beauty * m.getValue();
beauty--;
}
return sum;
}
}
