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();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9146357.html
今日推荐