如何在表中查找的话?的话、如何在

2023-09-11 04:47:24 作者:爷,桀骜不驯

这是一个编码的运动。假设有一个字母表和大量的词汇。我一定要找到表中的单词位置。一个字可以任意位置开始在表中,可定向或者垂直水平。 (我们可以假设,一个行/列只包含一个字)。

This is a coding exercise. Suppose there is a table of letters and a number of words. I have to find positions of the words in the table. A word may begin anywhere in the table and may be oriented either vertically of horizontally. (We can assume that a row/column may contain only one word).

例如:


table = xabcx
        xxxdx
        xxfex

words = ["abc", "edc", "fe"]

expected output is (0,1), (2,3), (2,2)

这种简单的解决办法是遍历所有的行/列,并检查各行/列包含任何的话。它采用 0(列数*行数*字数*字长)。有没有更好的解决办法?也许我应该pre-过程中的生字表,以建立一个更有效的数据结构?

The straightforward solution is to loop over all rows/columns and check if each row/column contains any of the words. It takes O(number of columns * number of rows * number of words * word length). Is there a better solution? Maybe I should pre-process the words list to build a more efficient data structure?

推荐答案

您可以使用特里数据结构来存储表。查一查的话是很容易的,一旦你拥有了特里。

You can use Trie data structure to store the table. Look up of words is very easy once you have the Trie.