2.5.14

question:

Sort by reverse domain. Write a data type Domain that represents domain names, including an appropriate compareTo() method where the natural order is in order if the reverse domain name. For example, the reverse domain of cs.princeton.edu is edu.princeton.cs. This is useful for web log analysis. Hint: Use s.split("\\.") to split the string s into tokens, delimited by dots. Write a client that reads domain names from standard input and prints the reverse domains in sorted order.

answer:

import edu.princeton.cs.algs4.*;
import java.util.Arrays;

public class Domain implements Comparable<Domain>
{
    private String[] string;
    private int n;
    
    public Domain(String name)
    {
        string = name.split("\\.");//将字符串name按里面的.来分成多个字符串再存储到string[]里面
        n = string.length;
    }
    
    public String toString() {//使最后输出的字符串顺序相反
        if (n == 0) return "";
        String s = string[0];
        for (int i = 1; i < n; i++)
            s = string[i] + "." + s;
        return s;
    }
    
    public int compareTo(Domain that)//按从后往前的字符串来比较
    {
        for(int i = Math.min(this.n, that.n); i >= 0; i--)
        {
            String a = this.string[i];
            String b = that.string[i];
            int c = a.compareTo(b);
            if(c < 0) 
                return -1;
            else if(c > 0)
                return 1;
        }
        return this.n - that.n;
    }
    
    public static void main(String[] args)
    {
        //输入apple.com cnn.com google.com princeton.edu cs.edu.princeton
        String[] names = StdIn.readStrings();
        Domain[] domains = new Domain[names.length];
        for (int i = 0; i < domains.length; i++) 
            domains[i] = new Domain(names[i]);

        for (int i = 0; i < domains.length; i++)
            StdOut.println(domains[i]);
    }
}

猜你喜欢

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