后缀数组(Suffix Array)是一种用于字符串排序和字符串相关问题的数据结构。它可以在 O(n log n) 的时间内构建出字符串的后缀数组,其中 n 是字符串的长度。后缀数组可以用于解决很多与字符串相关的问题,如最长公共子串、模式匹配等。
后缀数组的定义很简单:对于一个字符串 S,它的后缀数组 SA 是一个整数数组,其中 SA[i] 表示字符串 S 的后缀的起始位置,使得 S.substring(SA[i]) 是排在第 i 位的后缀。
以下是一个简单的 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
| import java.util.Arrays;
class Suffix implements Comparable<Suffix> { int index; String suffix;
public Suffix(int index, String suffix) { this.index = index; this.suffix = suffix; }
@Override public int compareTo(Suffix other) { return this.suffix.compareTo(other.suffix); } }
public class SuffixArray { public static int[] buildSuffixArray(String text) { int n = text.length(); Suffix[] suffixes = new Suffix[n];
for (int i = 0; i < n; i++) { suffixes[i] = new Suffix(i, text.substring(i)); }
Arrays.sort(suffixes);
int[] suffixArray = new int[n]; for (int i = 0; i < n; i++) { suffixArray[i] = suffixes[i].index; }
return suffixArray; }
public static void main(String[] args) { String text = "banana"; int[] suffixArray = buildSuffixArray(text);
System.out.println("Suffix Array:"); for (int index : suffixArray) { System.out.println(index + ": " + text.substring(index)); } } }
|
在上面的代码中,我们首先定义了一个 Suffix
类,用于表示后缀及其索引。然后,我们创建了一个 SuffixArray
类,其中的 buildSuffixArray
方法用于构建后缀数组。该方法首先创建一个 Suffix
对象数组,然后使用 Arrays.sort
对后缀数组进行排序,最后将排序后的索引数组返回。
注意,这只是一个简化的后缀数组实现示例。实际上,构建后缀数组有更高效的算法,如倍增算法和 DC3 算法。如果需要处理大规模字符串,建议使用这些更高效的算法。