001package algs63;  // section 6.3
002import stdlib.*;
003/* ***********************************************************************
004 *  Compilation:  javac KWIK.java
005 *  Execution:    java KWIK file.txt
006 *  Dependencies: StdIn.java In.java
007 *  Data files:   http://algs4.cs.princeton.edu/63suffix/tale.txt
008 *
009 *  %  java KWIK tale.txt 15
010 *  majesty
011 *   most gracious majesty king george th
012 *  rnkeys and the majesty of the law fir
013 *  on against the majesty of the people
014 *  se them to his majestys chief secreta
015 *  h lists of his majestys forces and of
016 *
017 *  the worst
018 *  w the best and the worst are known to y
019 *  f them give me the worst first there th
020 *  for in case of the worst is a friend in
021 *  e roomdoor and the worst is over then a
022 *  pect mr darnay the worst its the wisest
023 *  is his brother the worst of a bad race
024 *  ss in them for the worst of health for
025 *   you have seen the worst of her agitati
026 *  cumwented into the worst of luck buuust
027 *  n your brother the worst of the bad rac
028 *   full share in the worst of the day pla
029 *  mes to himself the worst of the strife
030 *  f times it was the worst of times it wa
031 *  ould hope that the worst was over well
032 *  urage business the worst will be over i
033 *  clesiastics of the worst world worldly
034 *
035 *************************************************************************/
036
037public class KWIK {
038
039        public static void main(String[] args) {
040                In in = new In(args[0]);
041                int context = Integer.parseInt(args[1]);
042
043                // read in text
044                String text = in.readAll().replaceAll("\\s+", " ");
045                int N = text.length();
046
047                // build suffix array
048                SuffixArray sa = new SuffixArray(text);
049
050                // find all occurrences of queries and give context
051                while (StdIn.hasNextLine()) {
052                        String query = StdIn.readLine();
053                        for (int i = sa.rank(query); i < N && sa.select(i).startsWith(query); i++) {
054                                int from = Math.max(0, sa.index(i) - context);
055                                int to   = Math.min(N-1, from + query.length() + 2*context);
056                                StdOut.println(text.substring(from, to));
057                        }
058                        StdOut.println();
059                }
060        }
061}