【问题标题】:Return the string in Trie返回 Trie 中的字符串
【发布时间】:2021-04-24 09:25:22
【问题描述】:

我有这个特里:

                a
               / \
              b   c
             / \   \
            t   y   u
           2     5   3
numbers at leaf stands for frequency, stored at the terminal node

我有默认的 Trie 搜索功能来搜索字符串。当我执行search('a') 时,它会返回aby,因为它是最常插入的字符串。频率由self.count 存储在我的函数中。 我不想发布我的代码。

您将如何解决并将节点从 a 返回到 y? 提前谢谢你。

【问题讨论】:

  • Id 在每个节点 ot trie 中创建一个元素,指示具有最大频率路径的子节点。然后根据这个索引进行深度优先搜索。
  • @AlbinPaul 每个节点(字母)都由 node.tree[index] 表示,其中 index 是字母的序号。我应该如何基于此做一个dfs?我没有使用也不会使用任何字典/集。
  • 好吧,找到一种机制,让每个节点都指向它需要遍历的下一个节点。不看你写了什么代码就不能说太多。

标签: python trie


【解决方案1】:

您可以使用递归生成器函数来遍历 trie 并生成所有包含搜索值作为子字符串的字符串:

简单的 trie 设置:

class Trie:
   def __init__(self, l=None):
      self.l, self.count, self.tree = l, 0, []
   def insert_l(self, word):
      if word:
         if not (n:=[i for i in self.tree if i.l == word[0]]):
            self.tree.append(Trie(word[0]))
            self.tree[-1].add_word(word)
         else:
            n[-1].add_word(word)
   def add_word(self, word):
      if self.l is not None:
         self.count += 1
      self.insert_l(word if self.l is None else word[1:])
      

现在,search 方法可以添加到Trie

class Trie:
    ...
    def search(self, word):
      def _search(t, c = []):
         if not t.tree:
            yield c+[t]
         else:
            for i in t.tree:
              yield from _search(i, c if t.l is None else c+[t])
      if (l:=[(j, i) for i in _search(self) if word in (j:=''.join(k.l for k in i))]):
         return max(l, key=lambda x:x[-1][-1].count)[0]

t = Trie()
words = ['abt', 'abt', 'aby', 'aby', 'aby', 'aby', 'aby', 'acu', 'acu', 'acu']
for word in words:
   t.add_word(word)

print(t.search('a'))

输出:

'aby'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多