01
02
03
04
05
06
07
08
09
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
47
48
package algs63; // section 6.3
import stdlib.*;
/* ***********************************************************************
 *  Compilation:  javac LRS.java
 *  Execution:    java LRS < file.txt
 *  Dependencies: StdIn.java SuffixArray.java
 *  Data files:   http://algs4.cs.princeton.edu/63suffix/tinyTale.txt
 *                http://algs4.cs.princeton.edu/63suffix/mobydick.txt
 *
 *  Reads a text string from stdin, replaces all consecutive blocks of
 *  whitespace with a single space, and then computes the longest
 *  repeated substring in that text using a suffix array.
 *
 *  % java LRS < tinyTale.txt
 *  'st of times it was the '
 *
 *  % java LRS < mobydick.txt
 *  ',- Such a funny, sporty, gamy, jesty, joky, hoky-poky lad, is the Ocean, oh! Th'
 *
 *  % java LRS
 *  aaaaaaaaa
 *  'aaaaaaaa'
 *
 *  % java LRS
 *  abcdefg
 *  ''
 *
 *************************************************************************/


public class LRS {

  public static void main(String[] args) {
    String text = StdIn.readAll().replaceAll("\\s+", " ");
    SuffixArray sa = new SuffixArray(text);

    int N = sa.length();

    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);
    }

    StdOut.println("'" + lrs + "'");
  }
}