Multi-word Search. Program Multiwordsearch.java reads a sequence of query words q[1], ..., q[k] from the command line and a sequence of docum Ents words d[1], ..., d[n] from standard input and finds the shortest interval in which the K words appear in the same Ord Er. (Here shortest means the number of words in the interval.) That was find indices I and j such that d[i1] = q[1], d[i2] = q[2], ..., d[ik] = Q[k] and I1 < I2 < ... < IK.
Answer: For each query word, create a sorted list of the indices where it appears in the document. Scan through lists 2 to K in so order, deleting indices at the front of each list until the first elements of the RE Sulting k lists is in ascending order.
The sequence of first elements on the lists forms the shortest interval containing the first element on List 1.
Now delete the first element on List 1. Repeatedly delete elements from the list 2 until it agrees with List 1. Repeat for List 3, and so on until the whole array are in ascending order. Check This sequence of first elements, etc.
1 /******************************************************************************2 * Compilation:javac Multiwordsearch.java3 * Execution:java multiwordsearch query1 query2 ... < input.txt4 * Dependencies:Queue.java Stdin.java5 *6 * Find The shortest interval (number of words) in the input file7 * that contains the "query words in the" order specified on the command line.8 *9 ******************************************************************************/Ten One Public classMultiwordsearch { A Public Static voidMain (string[] args) { -string[] Words =stdin.readallstrings (); - the //construct queues[j] = sequence of positions of jth query word -queue<integer>[] queues = (queue<integer>[])NewQueue[args.length]; - for(intj = 0; J < Args.length; J + +) { -QUEUES[J] =NewQueue<integer>(); + } - for(inti = 0; i < words.length; i++) { + for(intj = 0; J < Args.length; J + +) { A if(Words[i].equals (Args[j])) queues[j].enqueue (i); at } - } - - //repeatedly find smallest interval starting at position of Queues[0] - BooleanDone =false; - intBestlo =-1, Besthi =words.length; in while(!queues[0].isempty ()) { - intLo = queues[0].dequeue (); to intHi =Lo; + for(intj = 1; J < Args.length; J + +) { - while(!queues[j].isempty () && Queues[j].peek () <=hi) { the queues[j].dequeue (); * } $ if(Queues[j].isempty ()) {Panax NotoginsengDone =true; - Break; the } + ElseHi =Queues[j].peek (); A } the if(!done && Hi-lo < Besthi-Bestlo) { +Besthi =Hi; -Bestlo =Lo; $ } $ - } - the if(Bestlo >= 0) { - for(inti = Bestlo; I <= Besthi; i++)WuyiStdout.print (Words[i] + ""); the stdout.println (); - } Wu Else -Stdout.println ("Not FOUND"); About } $}
Algorithm Sedgewick Fourth Edition-1th chapter basic -023-multiwordsearch.java