File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
src/main/java/com/thealgorithms/strings Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .thealgorithms .strings ;
2
+
3
+ import java .util .Arrays ;
4
+
5
+ /**
6
+ * Suffix Array Implementation.
7
+ *
8
+ * This class constructs a Suffix Array for a given string.
9
+ *
10
+ */
11
+ public class SuffixArray {
12
+ private String text ;
13
+ private int [] suffixArray ;
14
+
15
+ public SuffixArray (String text ) {
16
+ this .text = text ;
17
+ this .suffixArray = buildSuffixArray ();
18
+ }
19
+
20
+ private int [] buildSuffixArray () {
21
+ int n = text .length ();
22
+ Integer [] suffixIndices = new Integer [n ];
23
+
24
+ // Initialize suffix indices
25
+ for (int i = 0 ; i < n ; i ++) {
26
+ suffixIndices [i ] = i ;
27
+ }
28
+
29
+ // Sort the suffix indices based on the suffixes
30
+ Arrays .sort (suffixIndices , (a , b ) -> text .substring (a ).compareTo (text .substring (b )));
31
+
32
+ // Convert Integer[] to int[]
33
+ int [] result = new int [n ];
34
+ for (int i = 0 ; i < n ; i ++) {
35
+ result [i ] = suffixIndices [i ];
36
+ }
37
+
38
+ return result ;
39
+ }
40
+
41
+ public int [] getSuffixArray () {
42
+ return suffixArray ;
43
+ }
44
+
45
+ public static void main (String [] args ) {
46
+ String text = "banana" ;
47
+ SuffixArray suffixArray = new SuffixArray (text );
48
+ System .out .println ("Suffix Array: " + Arrays .toString (suffixArray .getSuffixArray ()));
49
+ }
50
+ }
You can’t perform that action at this time.
0 commit comments