字典树(Trie)

字典树,也称为单词查找树or键树,是哈希树的变种。

应用:统计、排序,常用于搜索引擎用于文本词频统计。

利用字符串的公共前缀来降低查询时间开销以提供效率

以英文的字典树来说,26个字母对应每个节点最多26个子节点,单词长度不超过20,即树的层数不超过20层。

基本性质:

1.根节点不包含字符,除根节点外,每个节点都只包含一个字符

2.从根节点到子节点的路径是字符串

3.每个节点的子节点不重复

python版本的Trie树实现:

class Trie(object):

    def __init__(self):
        self.root={}
        self.end_of_word='#'


    def insert(self, word):
        """
        :type word: str
        :rtype: None
        """
        node=self.root
        for char in word:
            node=node.setdefault(char,{})
        node[self.end_of_word]=self.end_of_word


    def search(self, word):
        """
        :type word: str
        :rtype: bool
        """
        node=self.root
        for char in word:
            if char not in node:
                return False
            node=node[char]
        return self.end_of_word in node


    def startsWith(self, prefix):
        """
        :type prefix: str
        :rtype: bool
        """
        node=self.root
        for char in prefix:
            if char not in node:
                return False
            node=node[char]
        return True




# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)

单词搜索:212. 单词搜索 II - 力扣(LeetCode) (leetcode-cn.com)

from collections import defaultdict

class Trie:
    def __init__(self):
        self.children=defaultdict(Trie)
        self.word=" "
    
    def insert(self,word):
        cur=self
        for c in word:
            cur=cur.children[c]
        cur.is_word=True
        cur.word=word

class Solution(object):
    def findWords(self, board, words):
        """
        :type board: List[List[str]]
        :type words: List[str]
        :rtype: List[str]
        """
        def dfs(now,il,jl):
            if board[il][jl] not in now.children:
                return 
            ch=board[il][jl]
            now=now.children[ch]
            if now.word!=" ":
                ans.add(now.word)
            board[il][jl]="#"
            for i2,j2 in [(il+1,jl),(il-1,jl),(il,jl+1),(il,jl-1)]:
                if 0<=i2 <m and 0<=j2<n:
                    dfs(now,i2,j2)
            board[il][jl]=ch

        trie=Trie()
        for word in words:
            trie.insert(word)
        ans=set()
        m,n=len(board),len(board[0])
        for i in range(m):
            for j in range(n):
                dfs(trie,i,j)
        return list(ans)


            

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值