题解 | #名字的漂亮度#

名字的漂亮度

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

全部评论

相关推荐

05-19 15:21
已编辑
华南农业大学 Java
白火同学:你才沟通了200,说实话,北上广深杭这里面你连一座城市的互联网公司都没投满呢,更别说还有各种准一线二线城市了。等你沟通突破了三位数,还没结果再考虑转行的事吧。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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