题解 | #名字的漂亮度#

名字的漂亮度

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

全部评论

相关推荐

03-16 22:00
武汉大学 C++
幸福的小熊猫想要offer:我阿里投的 c++岗,面试官说自己是做 java 的,c++这辈子才有了
点赞 评论 收藏
分享
mjasjon:这种trash中厂 简历过筛概率比大厂还低(除阿里系)
投递哔哩哔哩等公司6个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务