题解 | #名字的漂亮度#
名字的漂亮度
https://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3
import java.util.*;
import java.util.Collections;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
int n = in.nextInt();
List<String> strList = new ArrayList<>();
for (int i = 0; i < n; i++) {
String str = in.next();
strList.add(str);
}
//System.out.println(strList);
for (String str : strList) {
//统计每个字母出现的次数
Map<Character, Integer> charAndCountMap = new HashMap<>();
for (int j = 0; j < str.length(); j++) {
char ch = str.charAt(j);
Integer count = charAndCountMap.get(ch);
if (count == null) {
charAndCountMap.put(ch, 1);
} else {
charAndCountMap.put(ch, count + 1);
}
}
//将map按value进行降序排序
Set<Map.Entry<Character, Integer>> myset = charAndCountMap.entrySet();
List<Map.Entry<Character, Integer>> list = new ArrayList<>(myset);
Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
@Override
public int compare(Map.Entry<Character, Integer> e1,
Map.Entry<Character, Integer> e2) {
return (e2.getValue()).compareTo(e1.getValue());
}
});
int score = 26;
int sum = 0;
for (Map.Entry<Character, Integer> entry : list) {
int count = entry.getValue();
sum += count * score;
score--;
}
System.out.println(sum);
}
}
}
}
逻辑很清晰:统计字母出现次数,最多的给分:26,依次减少,然后求和,输出即可。
给map排序:
map->EntrySet->List->自定义排序->遍历List,求总漂亮度
Collections.sort(list,new Comparator<Map.Entry<K,V>>(){}
@Override
public int compare(Map.Entry<K,V> e1,Map.Entry<K,V> e2){
return e2.getValue.compareTo(e1.getValue());
}
);
