Skip to content

Commit f14797f

Browse files
author
ACHAUHA2
committed
git commit -m "Added Suffix Array algo in Java"
1 parent 0d68b65 commit f14797f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}

0 commit comments

Comments
 (0)