public class LongestRepeatedSubstring {
// Do not instantiate.
private LongestRepeatedSubstring() { }
/**
* Returns the longest common string of the two specified strings.
*
* @param s one string
* @param t the other string
* @return the longest common string that appears as a substring
*/
/**
* Returns the longest repeated substring of the specified string.
*
* @param text the string
* @return the longest repeated substring that appears in {@code text};
* the empty string if no such string
*/
public static String lrs(String text) {
int n = text.length();
SuffixArray sa = new SuffixArray(text);
String lrs = "";
for (int i = 1; i < n; i++) {
int length = sa.lcp(i);
if (length > lrs.length()) {
// lrs = sa.select(i).substring(0, length);
lrs = text.substring(sa.index(i), sa.index(i) + length);
}
}
return lrs;
}
/**
* Unit tests the {@code lrs()} method.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String text = StdIn.readAll().replaceAll("\\s+", " ");
StdOut.println("'" + lrs(text) + "'");
}
}
public class SuffixArray {
public Suffix[] suffixes;
public SuffixArray(String text) {
int n= text.length();
this.suffixes = new Suffix[n];
for (int i = 0; i < n; i++) {
suffixes[i] = new Suffix(text, i);
}
Arrays.sort(suffixes);
}
private static class Suffix implements Comparable<Suffix> {
private final String text;
private final int index;
private Suffix(String text, int index) {
this.text = text;
this.index = index;
}
private int length() {
return text.length() - index;
}
private char charAt(int i) {
return text.charAt(index + i);
}
@Override
public int compareTo(Suffix that) {
if (this == that) return 0;
int n = Math.min(this.length(), that.length());
for (int i = 0; i < n; i++) {
if (this.charAt(i) < that.charAt(i)) return -1;
if (this.charAt(i) > that.charAt(i)) return +1;
}
return this.length() - that.length();
}
}
public int length() {
return suffixes.length;
}
public int index(int i) {
if (i < 0 || i >= suffixes.length) throw new IllegalArgumentException();
return suffixes[i].index;
}
/**
* Returns the length of the longest common prefix of the <em>i</em>th
* smallest suffix and the <em>i</em>-1st smallest suffix.
* @param i an integer between 1 and <em>n</em>-1
* @return the length of the longest common prefix of the <em>i</em>th
* smallest suffix and the <em>i</em>-1st smallest suffix.
* @throws java.lang.IllegalArgumentException unless {@code 1 <= i < n}
*/
public int lcp(int i) {
if (i < 1 || i >= suffixes.length) throw new IllegalArgumentException();
return lcpSuffix(suffixes[i], suffixes[i-1]);
}
// longest common prefix of s and t
private static int lcpSuffix(Suffix s, Suffix t) {
int n = Math.min(s.length(), t.length());
for (int i = 0; i < n; i++) {
if (s.charAt(i) != t.charAt(i)) return i;
}
return n;
}
}
Longest Repeating Substring + 最长重复子串 + 后缀数组
最新推荐文章于 2021-11-30 15:11:25 发布