0

I came across below program which looks perfect. Per me its time complexity is nlogn where n is the length of String.

n for storing different strings,nlog for sorting, n for comparison. So time complexity is nlogn. Space complexity is n for storing the storing n substrings

My question is can it be further optimized ?

public class LRS {


    // return the longest common prefix of s and t
    public static 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);
    }


    // return the longest repeated string in s
    public static 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;
    }



    public static void main(String[] args) {
        String s = "MOMOGTGT";
        s = s.replaceAll("\\s+", " ");
        System.out.println("'" + lrs(s) + "'");

    }

}
Deepak Kumar
  • 1,669
  • 3
  • 16
  • 36
user3198603
  • 5,528
  • 13
  • 65
  • 125
  • 2
    If the code be already running, then this might belong on [Code Review](http://codereview.stackexchange.com). – Tim Biegeleisen Oct 16 '16 at 12:37
  • You can make it better faster (though not asymptotically) by not creating as many substrings. For instance, `lcp` could just return prefix length, and you keep `i` and that return value to store the "maximum so far". – Andy Turner Oct 16 '16 at 13:02
  • Andy is right. In fact, when you create all the substrings it's already O(n^2), and when you sort the suffixes, it's acutally O(n^2 logn) – Jinghan Wang Mar 08 '19 at 02:31

1 Answers1

-2

Have a look at this algorithm given in geeksforgeeks, this might be helpful:

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