2.5.8
Posted w-j-c
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2.5.8相关的知识,希望对你有一定的参考价值。
question:
Write a program Frequency that reads strings from standard input and prints the number of times each string occurs, in descending order of frequency.
answer:
//我把官网的答案拿来改了下
//就是先把输入排序,放到自己定义的类里,然后次数排序
import edu.princeton.cs.algs4.*; import java.util.Arrays; public class Frequency { private static class Record implements Comparable<Record> { String string; int N; public Record(String a, int num) { string = a; N = num; } public int compareTo(Record that) { return this.N - that.N; } public void show() { StdOut.print(string + " " + N); } } public static void main(String[] args) { String[] a = StdIn.readAllStrings(); int n = a.length; Arrays.sort(a); Record[] records = new Record[n]; String word = a[0]; int freq = 1; int m = 0; for (int i = 1; i < n; i++) { if (!a[i].equals(word)) { records[m++] = new Record(word, freq); word = a[i]; freq = 0; } freq++; } records[m++] = new Record(word, freq); Arrays.sort(records, 0, m); for (int i = m-1; i >= 0; i--) { records[i].show(); StdOut.println(); } } }
以上是关于2.5.8的主要内容,如果未能解决你的问题,请参考以下文章