Amazon Interview - Longest Repeated Substring

Given a text string, find Longest Repeated Substring in the text. If there are more than one Longest Repeated Substrings, get any one of them.

Longest Repeated Substring in GEEKSFORGEEKS is: GEEKS
Longest Repeated Substring in AAAAAAAAAA is: AAAAAAAAA
Longest Repeated Substring in ABCDEFG is: No repeated substring
Longest Repeated Substring in ABABABA is: ABABA
Longest Repeated Substring in ATCGATCGA is: ATCGA
Longest Repeated Substring in banana is: ana
Longest Repeated Substring in abcpqrabpqpq is: ab (pq is another LRS here)

Solution 1:

Using Suffix Array. Time complexity: O(nlogn), Space complexity: O(n)

// return the longest repeated string in s
public String lrs(String s) {
    // form the N suffixes
    int N  = s.length();
    String[] suffixes = new String[N];
    for (int i = 0; i < N; i++) {
        suffixes[i] = s.substring(i, N);
    }
    // sort them
    Arrays.sort(suffixes);

    // find longest repeated substring by comparing adjacent sorted suffixes
    String lrs = "";
    for (int i = 0; i < N - 1; i++) {
        String x = lcp(suffixes[i], suffixes[i+1]);
        if (x.length() > lrs.length())
            lrs = x;
    }
    return lrs;
}

// return the longest common prefix of s and t
public String lcp(String s, String t) {
    int n = Math.min(s.length(), t.length());
    for (int i = 0; i < n; i++) {
        if (s.charAt(i) != t.charAt(i))
            return s.substring(0, i);
    }
    return s.substring(0, n);
}

Reference:

http://introcs.cs.princeton.edu/java/42sort/LRS.java.html 

 

Solution 2:

Using Suffix TreeTime complexity: O(n), Space complexity: O(n)

 

Reference:

http://www.geeksforgeeks.org/suffix-tree-application-3-longest-repeated-substring/

你可能感兴趣的:(substring)