package edu.princeton.cs.algs4; import edu.princeton.cs.introcs.*; /************************************************************************* * 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); lrs = text.substring(sa.index(i), sa.index(i) + length); } } StdOut.println("'" + lrs + "'"); } } /************************************************************************* * Copyright 2002-2012, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4-package.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4-package.jar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * algs4-package.jar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with algs4-package.jar. If not, see http://www.gnu.org/licenses. *************************************************************************/