题解 | #名字的漂亮度#

名字的漂亮度

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

import java.util.*;

// 使用比较器写的,很通用的方法
// 输入的时候因为有int 有 string 所以要加终止条件
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) {
            String next = in.nextLine();
            if (next == null || next == "") break;
            int num = Integer.parseInt(next);
            LinkedHashMap<Character, Integer> charCnt = new LinkedHashMap<>();
            String[] totalStr = new String[num];
            for (int i = 0; i < num; i++) {
                totalStr[i] = in.nextLine();
            }

            for (int i = 0; i < num; i++) {
                charCnt = new LinkedHashMap<>();
                for (int j = 0; j < totalStr[i].length(); j++) {
                    char curCh = totalStr[i].charAt(j);
                    charCnt.put(curCh, charCnt.containsKey(curCh) ? charCnt.get(curCh) +  1 : 1);
                }
                List<Map.Entry<Character, Integer>> entryList = new ArrayList<>(charCnt.entrySet());
                Collections.sort(entryList, new Comparator<Map.Entry<Character, Integer>>() {
                    public int compare(Map.Entry<Character, Integer> v1, Map.Entry<Character, Integer> v2) {
                        return v2.getValue().compareTo(v1.getValue());
                    }
                });
                int ans = 0;
                for (int k = 0; k < charCnt.size(); k++) {
                    ans += entryList.get(k).getValue() * (26 - k);
                }
                System.out.println(ans);
            }
        }
    }
}

全部评论

相关推荐

双尔:你就写拥有ai开发经历,熟练运用提示词,优化ai,提高ai回答质量
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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