题解 | #名字的漂亮度#
名字的漂亮度
https://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
int num = Integer.parseInt(sc.nextLine());
List<String> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
list.add(sc.nextLine());
}
for (String s : list) {
System.out.println(findMaxBeautiful(s));;
}
}
sc.close();
}
/**
* 找最大漂亮数
* @param s
* @return
*/
private static int findMaxBeautiful(String s) {
//将字符保存在hashMap中,如果重复字符数量++
Map<Character, Integer> map = new HashMap<>();
for (Character c : s.toCharArray()) {
if (!map.containsKey(c)) {
map.put(c, 1);
} else {
map.put(c, map.get(c) + 1);
}
}
//按照出现字母最大排序,重写排序
List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
list.sort((o1, o2) -> o2.getValue() - o1.getValue());
//将出现次数最多字符指定最大数,并且使用后递减
int maxSum = 0, maxIndex = 26;
for (Map.Entry<Character, Integer> entry : list) {
maxSum += entry.getValue() * maxIndex;
maxIndex --;
}
return maxSum;
}
}