Given an n by m letter grid and p query words, find for each word the longest contiguous substring that can be placed along a row or column in one of four directions.
Medium6Brute forceImplementationStringArrayNo attempts yetTime limit2sMemory limit512 MBYoungsun is a sham fortune teller. She tells fortunes with a very simple method and uses it to decide how much luck a person has.
Each cell of an n×m grid holds one letter. A visitor writes down any word of length k. Youngsun lays the word over the grid so that a contiguous part of the word matches the letters of the grid for as long a stretch as possible, and the length of that matched contiguous part decides the amount of luck.
The word is laid in a straight line parallel to the rows or the columns, and its letters can run in any of the four directions: up, down, left, or right. Letters that do not match are allowed to hang outside the grid.
For example, take the grid below, where (r,c) is the cell in row r and column c.
ABCDE
FGHIJ
KLMNO
PQRST
UVWXY
For the word AHMRVP, the contiguous part HMR can be laid from (2,3) to (4,3). For the word JEHGFP, the contiguous part HGF can be found from (2,3) to (2,1).
Youngsun is a sham, but her fortunes happen to come true, so she is surprisingly popular. Today she has to read the fortunes of p people, but she is off spending the money she earned from fortune telling. Find each word in the grid on her behalf.
The first line contains the grid size n and m. (1≤n,m≤100)
Each of the next n lines contains the m letters of one grid row, without spaces.
The next line contains the number of visitors p and the word length k. (1≤p≤100000, 1≤k≤30)
Each of the next p lines contains the k letters of the word one visitor wrote, without spaces.
Every letter in the grid and in the words is an uppercase English letter.
For each word, in input order and one per line, print the length of the longest contiguous part of the word that can be laid over the grid so that it matches. If no letter of the word appears in the grid, print 0.