前缀树(Trie)

定义:

前缀树(Trie树),即字典树,又称单词查找树或键树,是一种树形结构。核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。

优点:

最大限度地减少无谓的字符串比较,查询效率比哈希表高。

与哈希表对比

哈希表可以在 O(1)O(1) 时间内寻找键值,却无法高效的完成以下操作:
1.找到具有同一前缀的全部键值。
2.按词典序枚举字符串的数据集。
随着哈希表大小增加,会出现大量的冲突,时间复杂度可能增加到 O(n),其中 nn是插入的键的数量

前缀树的构建

在这里插入图片描述

查询

在这里插入图片描述

代码实现python:

class Trie(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.dict = {}
        self.end = -1

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: None
        """
        curdict = self.dict
        for char in word:
            if char not in curdict:
                curdict[char] = {}
            curdict = curdict[char]
            print(self.dict)
        curdict[self.end] = True

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        curdict = self.dict
        for char in word:
            if char not in curdict:
                return False
            curdict = curdict[char]   
        return self.end in curdict

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        curdict = self.dict
        for char in prefix:
            if char not in curdict:
                return False
            curdict = curdict[char]
        return True

用途:

1.自动补全
2.拼写检查
3.IP路由

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值