Trie(字典树)

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

前缀树特点:

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

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

  ③:根节点不包含字母

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

  ⑤:因为我是用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

                

转载于:https://www.cnblogs.com/python-zkp/p/10505277.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值