python3 Trie树及其应用

关于前缀树基础知识就不介绍了,通俗总结就是从根节点出发,每个节点都有两个属性,一个是这个节点的所有子节点(python3用一个字典记录这个节点所有后续节点即可)和一个标志,标志是否是一个字符串的结束。对于前缀树而言通常需要有查询与插入两种操作。查询的话就是从根节点出发,依次查找根节点的子节点是否有对应的字符,直到字符结束。插入的话也是从根节点出发,依次查找当前节点的子节点是否有对应的字符,有就不需要重新生成,没有的话就重新生成一个前缀树节点,直到最后一个字符插入完毕。具体实现如下所示:

from collections import defaultdict
class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.is_word = False
class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        cur = self.root
        for w in word:
            cur = cur.children[w]
        cur.is_word = True

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        cur = self.root
        for w in word:
            if w not in cur.children:
                return False
            cur = cur.children[w]
        return cur.is_word

    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """

        cur = self.root
        for w in prefix:
            if w not in cur.children:
                return False
            cur = cur.children[w]
        return True

关于前缀树的应用,参见力扣472

前缀树实现:

from collections import defaultdict
class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.is_word = False

class Trie:
    def __init__(self,words):
        self.root = TrieNode()
        for word in words:
            self.insert(word)
    def insert(self,word:str):
        cur = self.root
        for item in word:
            cur = cur.children[item]
        cur.is_word = True

class Solution:
    def findAllConcatenatedWordsInADict(self, words:list):
        Trie_ = Trie(words)
        ans = []
        def dfs(i,word,cur,is_cut):
            if i == len(word):
                return cur.is_word and is_cut
            if cur.is_word:
                if dfs(i,word,Trie_.root,True):
                    return True

            if word[i] not in cur.children:
                return False
            else:
                return dfs(i+1,word,cur.children[word[i]],is_cut)
        for word in words:
            if dfs(0,word,Trie_.root,False):
                ans.append(word)
        return ans

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值