码迷,mamicode.com
首页 > 其他好文 > 详细

2.5.8

时间:2018-06-06 21:37:45      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:record   occurs   answer   style   rds   nts   print   write   order   

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

标签:record   occurs   answer   style   rds   nts   print   write   order   

原文地址:https://www.cnblogs.com/w-j-c/p/9146357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!