字符统计
字符统计
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); } } }