字符统计

字符统计

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

依旧是priorityQueue

import java.util.*;

class Pair implements Comparable<Pair>{
    private int value;
    private int times;
    public Pair(int value, int times) {
        this.value = value;
        this.times = times;
    }
    public int compareTo(Pair that) {
        if (this.times == that.times) {
            return this.value - that.value;
        }
        return that.times - this.times;
    }
    public char get() {
        return (char)value;
    }
}

public class Main {

    private final int N = 127;
    public Main() {
    }

    public String count(String str) {
        int[] arr = new int[N];
        for (char ch : str.toCharArray()) {
            if (ch >= N) continue;
            arr[ch]++;
        }
        PriorityQueue<Pair> pq = new PriorityQueue<>();
        for (int i = 0; i < N; i++) {
            if (arr[i] != 0) { 
                pq.offer(new Pair(i, arr[i]));
            }
        }
        StringBuilder res = new StringBuilder();
        while (!pq.isEmpty()) {
            res.append(pq.poll().get());
        }
        return res.toString();
    }

    public static void main(String[] args) {
        Main solution = new Main();
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String str = in.nextLine();
            String res = solution.count(str);
            System.out.println(res);
        }

    } 
}
全部评论

相关推荐

11-17 11:15
门头沟学院 Java
金山办公终于发offer了,但薪资和平台都不如已有的offer打算拒了,A不了薪资,不满意直接拒了,留给需要的人嘿嘿嘿时间线:10.14线下一面&nbsp;,10.23线上二面,下午发测评,11月1日HR面,11月14日电话谈薪,11月17日直接发offer
star__plat...:好兄弟干的好啊,解气。金山第一次笔难度高的离谱,第二次简单的离谱全A了,用人部门筛选中估计最后还是要挂我,就这今早智联招聘还给我发信息让我投
offer帮选
点赞 评论 收藏
分享
09-29 15:34
已编辑
北京航空航天大学 C++
做个有文化的流氓:结果是好的,过程不重要,而且你的offer太多了
软开人,秋招你打算投哪些...
点赞 评论 收藏
分享
评论
4
1
分享

创作者周榜

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