首页 > 其他 > 详细

Trie(字典树)

时间:2019-03-10 15:24:35      阅读:187      评论:0      收藏:0      [点我收藏+]

字典树的作用:它是利用单词的公共前缀来节约储存空间,因为单词的前缀相同就会公用前缀的节点。比如搜索提示就可以根据输入的前缀来提示可以构成的单词。

前缀树特点:

  ①:单词前缀相同共用节点。

  ②:每个节点只存一个字母

  ③:根节点不包含字母

  ④:组成的单词是根据所走过的路径所决定的

  ⑤:因为我是用Python字典实现的所以数的子节点存在它的key中,没一个单词结束要有一个判断决定它是一个单词的结尾不然比如 输入apple如果search(‘app‘)就不能判断插入了这个单词了。

  ⑥:儿子节点数量不定

代码:

class Trie:

  def __init__(self, root):

    self.root = {}

  def insert(self, sequence):

    #从头结点开始插入

    node = self.root

    for item in sequence:

      if item not  in node.keys():

        node.[item] = {}

      node = node[item]

    #此时到了单词的结尾,插入一个判断词

    node[‘end‘] = True

  def search(self, word):

    curnode = self.root

    for w in word:
      if w not in node.keys():
        return False
      else:
        node = node[w]
    mark = node.get(‘end‘)
    return mark is not None

  def startsWith(self, prefix):
    curnode = self.root
    for w in prefix:
      if w not in curnode.keys():
        return False
      curnode = curnode[w]
    return True

if __name__ == "__main__":

  t = Trie()
  t.insert(‘apple‘)
  assert not t.search(‘app‘)
  assert t.search(‘apple‘)
  t.insert(‘app‘)
  assert t.search(‘app‘)
  assert t.startsWith(‘app‘)

 

leetcode: https://leetcode-cn.com/problems/implement-trie-prefix-tree/submissions/

我的github代码:https://github.com/pythonkd/python/blob/master/LeetCode/trie.py

                

Trie(字典树)

原文:https://www.cnblogs.com/python-zkp/p/10505277.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!