本打算周末完成这次作业,但没想到遇到了hard deadline,刚开始看不懂题意,后来发现算法4书上有个类似的问题,才理解了题意。最后晚上加班,上课加班,还好在11:35也就是课程结束前25分钟完成了这次作业。。。

本次作业学到的知识点:

1、java中两个类对象比较相等用equals,因此String对象也应用equals方法,而非“==”。

2、读取命令行参数用args[i],读取文件中的数据才用StdIn等。

3、String对象的长度用方法length,数组的长度用length()

4、类似于int在泛型中用Integer类,char在泛型中应用Charactor类。

5、用Arrays.sort方法对数组进行自定义排序,首先数组应为基本类型对应的类,然后要重载compare方法,这里参考别人的代码使用了匿名内部类,详见CircularSuffixArray类中构造函数。而对基本类型的数组排序,函数参数为数组名即可(见BurrowsWheeler类44行)。

作业中难以理解的一些地方:

1、后缀数组排序是指将每一行中的后缀字符数组看做字符串进行排序。

2、不需要讲后缀数组存储起来,因为如果字符数组在第n行,那么数组就以输入字符串中的第n个字符开始,从而根据输入字符串就可确定此字符数组。

3、BurrowsWheeler类的逆变换中,通过t数组构造一个<字符,字符在t数组中的下标的队列>的符号表,就可以方便的求出next数组。

 1 import java.util.List;
 2 import java.util.ArrayList;
 3 import edu.princeton.cs.algs4.BinaryStdIn;
 4 import edu.princeton.cs.algs4.BinaryStdOut;
 5 
 6 public class MoveToFront {
 7     // apply move-to-front encoding, reading from standard input and writing to standard output
 8     public static void encode()
 9     {
10         List<Character> list = new ArrayList<Character>();
11         for (int i = 0; i < 256; i++)
12             list.add((char)i);
13         while (!BinaryStdIn.isEmpty())
14         {
15             char c = BinaryStdIn.readChar();
16             int index = list.indexOf(c);
17             BinaryStdOut.write(index, 8);
18             list.remove(index);
19             list.add(0, c);
20         }
21         BinaryStdOut.close();
22     }
23 
24     // apply move-to-front decoding, reading from standard input and writing to standard output
25     public static void decode()
26     {
27         List<Character> list = new ArrayList<Character>();
28         for (int i = 0; i < 256; i++)
29             list.add((char)i);
30         while (!BinaryStdIn.isEmpty())
31         {
32             int index = BinaryStdIn.readChar();
33             char c = list.get(index);
34             BinaryStdOut.write(c);
35             list.remove(index);
36             list.add(0, c);
37         }
38         BinaryStdOut.close();
39     }
40 
41     // if args[0] is '-', apply move-to-front encoding
42     // if args[0] is '+', apply move-to-front decoding
43     public static void main(String[] args)
44     {
45         if (args[0].equals("-")) encode();
46         if (args[0].equals("+")) decode();
47     }
48 }
View Code

相关文章:

  • 2021-12-29
  • 2021-10-03
  • 2021-12-19
  • 2021-07-08
  • 2021-07-04
  • 2021-08-04
  • 2021-05-16
  • 2021-09-21
猜你喜欢
  • 2021-08-30
  • 2022-12-23
  • 2021-12-06
  • 2021-10-26
  • 2021-12-16
  • 2021-09-13
  • 2022-03-08
相关资源
相似解决方案