题解 | #名字的漂亮度# 使用map转list并自定义比较

名字的漂亮度

https://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();
        // 使用map记录字符串中每个字母(key)出现的次数(value)
        for (int i = 0; i < n; i++) {
            TreeMap<Character, Integer> map = new TreeMap<>();
            String string = scanner.next();
            for (char c : string.toCharArray()) {
                if (!map.containsKey(c)){
                    map.put(c,1);
                } else {
                    map.put(c, map.get(c) + 1);
                }
            }
            // 将map转换为List
            List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
            // 转换为List便于使用Collections.sort()方法进行排序
            Collections.sort(list,new MyComparator());

            int max = 26;
            int sum = 0;
            for (Map.Entry<Character, Integer> entry : list) {
                sum += entry.getValue() * (max--);
            }
            System.out.println(sum);
        }
    }
}
class MyComparator implements Comparator<Map.Entry<Character, Integer>> {
    // 重写方法,自定义比较方式
    @Override
    public int compare(Map.Entry<Character, Integer> o1,
                       Map.Entry<Character, Integer> o2) {
        return o2.getValue() - o1.getValue();
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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