题解 | #名字的漂亮度#

贪心算法,将名字中出现的字母按照频率排序,频率越高的权重越高。

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;
    }
}


全部评论

相关推荐

不愿透露姓名的神秘牛友
10-11 19:51
已编辑
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务