-
Notifications
You must be signed in to change notification settings - Fork 0
/
CircularSuffixArray.java
105 lines (92 loc) · 2.86 KB
/
CircularSuffixArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/******************************************************************************
* Compilation: javac CircularSuffixArray.java
* Execution: java CircularSuffixArray filename.txt
* Dependencies: In / Arrays
*
* Creates circularSuffixArray Based on the given string s.
*
* % java CircularSuffixArray abra.txt
* Length of string is: 12
* Indexes are as follows:
* 11
* 10
* 7
* 0
* 3
* 5
* 8
* 1
* 4
* 6
* 9
* 2
*
******************************************************************************/
import edu.princeton.cs.algs4.In;
import java.util.Arrays;
/**
* This class provides methods for printing strings and numbers to standard output.
*
* @author Dumitru Hanciu
*/
public class CircularSuffixArray {
private Integer[] index;
public CircularSuffixArray(String s) {
if (s == null)
throw new IllegalArgumentException("String must not be null.");
int length = s.length();
char[] chars = s.toCharArray();
index = new Integer[length];
// initialize each array position with its location
for (int i = 0; i < s.length(); i++)
index[i] = i;
// sort the index array using the given comparator
Arrays.sort(index, (Integer i1, Integer i2) -> {
int com = chars[i1] - chars[i2];
for (int count = 0; com == 0 && count < length; count++) {
int substringAIndex = ++i1 % length;
int substringBIndex = ++i2 % length;
char charA = chars[substringAIndex];
char charB = chars[substringBIndex];
com = Character.compare(charA, charB);
}
return com;
});
}
/**
* Returns the length of s.
*
* @return the length of s
*/
public int length() {
return index.length;
}
/**
* Returns index of ith sorted suffix.
*
* @param i the ith sorted sufix
* @return the index of ith sorted suffix
* @throws IllegalArgumentException if {@code i < 0 || i >= index.length}
*/
public int index(int i) {
if (i < 0 || i >= index.length)
throw new IllegalArgumentException("provided index \"" + i + "\"" +
" does not satisfy: 0 <= i < length");
return index[i];
}
/**
* Unit tests the {@code CircularSuffixArray} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
In in = new In(args[0]);
String str = in.readString();
CircularSuffixArray abra = new CircularSuffixArray(str);
System.out.println("Length of string is: " + abra.length());
System.out.println("Indexes are as follows: ");
for (int i = 0; i < abra.length(); i++) {
System.out.println(abra.index(i));
}
}
}