题解 | 字符统计

#牛客创作赏金赛# #刷题我是认真的#

解题思路:

  1. 这个是有点偷懒的,直接参考了别人的的答案,使用map的sorted排序
import java.util.HashMap;
import java.util.*;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        char[] arr = in.nextLine().toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        for (char c : arr) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        List<Character> entryList = map.entrySet().stream()
                                    .sorted(Map.Entry.comparingByKey())
                                    .sorted((o1, o2)->Integer.compare(o2.getValue(), o1.getValue()))
                                    .map(Map.Entry::getKey)
                                    .collect(Collectors.toList());
        entryList.forEach(System.out::print);;
    }
}

其他思路:

1. 使用优先队列

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int[] a = new int[128]; // 统计字符出现次数

        for (char c : s.toCharArray()) {
            a[(int) c]++;
        }

        // 使用优先队列按出现次数排序
        PriorityQueue<Character> pq = new PriorityQueue<>((c1, c2) -> a[c2] - a[c1]);
        for (int i = 0; i < a.length; i++) {
            if (a[i] > 0) {
                pq.offer((char) i);
            }
        }

        // 输出结果
        while (!pq.isEmpty()) {
            System.out.print(pq.poll());
        }
    }
}

}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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