【发布时间】:2023-08-30 02:21:01
【问题描述】:
问题
给定一个字符串列表,从列表中找出给定文本中出现的字符串。
示例
list = ['red', 'hello', 'how are you', 'hey', 'deployed']
text = 'hello, This is shared right? how are you doing tonight'
result = ['red', 'how are you', 'hello']
'red' 因为它有 'shared' 有 'red' 作为子字符串
- 这与this question 非常相似,只是我们需要查找的单词也可以是子字符串。
- 该列表非常大,并且会随着用户的增加而增加,而不是整个长度几乎相同的文本。
- 我正在考虑一个解决方案,其中时间复杂度取决于文本长度而不是单词列表,以便即使添加大量用户也可以扩展。
解决方案
- 我从给出的单词列表中构建了一个 trie
- 对文本运行 dfs 并根据 trie 检查当前单词
伪代码
def FindWord (trie, text, word_so_far, index):
index > len(text)
return
//Check if the word_so_far is a prefix of a key; if not return
if trie.has_subtrie(word) == false:
return
//Check if the word_so_far is a key; if ye add to result and look further
if trie.has_key(word) == false:
// Add to result and continue
//extend the current word we are searching
FindWord (trie, text, word_so_far + text[index], index + 1)
//start new from the next index
FindWord (trie, text, "", index + 1)
问题在于,虽然运行时现在取决于 len(text),但它在构建 trie 后以时间复杂度 O(2^n) 运行,这对于多个文本来说是一次性的,所以没问题。
我没有看到任何重叠的子问题来记忆和改进运行时。
您能否建议任何方法我可以实现依赖于给定文本的运行时,而不是可以按每个处理和缓存的单词列表,并且也比这更快。
【问题讨论】:
-
你试过什么?您有自己的工作代码示例吗?
-
我已经发布了我所做的伪代码。实际代码有很多不相关的部分,可能会分散实际问题的注意力
-
@JordanSinger OP 已经对他的尝试给出了合理的信息描述,因此无需发布实际代码,因为实际问题在于 算法。
-
您多久从同一索引处的“”递归重新启动? (或者以其他方式重复之前的起点,需要大量工作重做)也许根据元组键(word_so_far,index)创建一个计数器,看看是否发生这种情况。
标签: python algorithm search trie