字符统计(JAVA)

字符统计

http://www.nowcoder.com/questionTerminal/c1f9561de1e240099bdb904765da9ad0

PriorityQueue + HashMap

定义比较方式两种:override compareTo() / lambda表达式

遍历map两种方法:forEach() + lambda表达式 / Map.Entry<>

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.PriorityQueue;


public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()) {
            String s = in.nextLine();
            Map<Character, Integer> map = new HashMap<Character, Integer>();
            for(int i = 0; i < s.length(); i++) {
                char cur = s.charAt(i);
               map.put(cur, map.getOrDefault(cur, 0) + 1);
            }
            PriorityQueue<Point> pq = new PriorityQueue<>();
            /*
            PriorityQueue<Point> pq = new PriorityQueue<>((x, y) -> -128*(x.number - y.number) + (int)(x.c - y.c));
            for (Map.Entry<Character, Integer> entry : map.entrySet()) {
                Point p = new Point(entry.getKey(), entry.getValue());
                pq.offer(p);
            }
            */
            map.forEach((k, v) -> pq.offer(new Point(k, v)));
            StringBuilder res = new StringBuilder();
            while (!pq.isEmpty()) {
                res.append(pq.poll().c);
        }
        System.out.println(res.toString());
        }
    }
}
class Point implements Comparable<Point>{
    char c;
    int number;
    Point(char c, int number){
        this.c = c;
        this.number = number;
    }
    @Override
    public int compareTo(Point p2){
        if (p2.number != this.number){
            return p2.number - this.number;
        }else {
            return (int)(this.c - p2.c);
        }
    }
}

全部评论
next() 读不了空格吧
1 回复 分享
发布于 2020-07-28 22:18

相关推荐

美团 后端开发 总包n(15%是股票)
点赞 评论 收藏
分享
11-03 14:38
重庆大学 Java
AAA求offer教程:我手都抬起来了又揣裤兜了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务