如何在python中表示为词典字典的树中搜索单词?

时间:2015-09-03 04:50:07

标签: python dictionary trie

我有一个像这样的词典 -

{"a": {"b": {"e": {},
             "f": {},
             "g": {"l": {},
                   "m": {},
                   "n": {}}},
       "c": {"h": {},
             "i": {}},
       "d": {"j": {},
             "k": {}}}}

这是一个像这样翻译的树状结构

            a   
          /  |\
         /   | \
        /    |  \
       /     |   \
      /      |    \
     /       |     \
    b        c      d
  / | \      | \    |\
e   f  g     h  i   j k
      / |\  
     l  m n

我有一个字符列表 - [a, c, h, q, r] 我想找出字典中是否存在给定的单词(字符列表),如果它没有,则从存在的开头返回最长的子序列。如果是,请返回相同的列表。

在上面的示例中,返回值应为 - [a, c, h]

1 个答案:

答案 0 :(得分:1)

编辑 - 感谢您将数据更新为有意义的内容。

穿越特里非常有趣。这是一个快速演示。

trie = {"a": {"b": {"e": {},
                    "f": {},
                    "g": {"l": {},
                          "m": {},
                          "n": {}}},
              "c": {"h": {},
                    "i": {}},
              "d": {"j": {},
                    "k": {}}}}

target = 'achqr'
sub_trie = trie
longest_sequence = []
for c in target:
    sub_trie = sub_trie.get(c)
    if sub_trie is None:  # the letter being looked for doesn't exist after this sequence
        break
    longest_sequence.append(c)  # track the sequence since the trie is not reverse linked
print(longest_sequence)