LeetCode----字典树

1 原理

字典树原理参考

2 构建字典树

class Trie:

    def __init__(self):
        # 字典树结构
        # children 数组用于存储字符,数组下标位置 当不为空时意味存在这个字符
        # isEnd 用于标记是否到达单词尾
        self.children = [None] * 26
        self.isEnd = False

    def insert(self, word: str) -> None:
        # 将node 指向根节点
        node = self
        for ch in word:
            # 获取当前字符所对应的下标
            num = ord(ch) - ord("a")
            # 如果节点中children数组的num下标为空,则不存在当前字符。
            # 在当前下标下创建 一个 Trie()  节点
            if not node.children[num]:
                node.children[num] = Trie()
            # node指向下一层 node
            node = node.children[num]
        # 字符全部插入完毕,在最后一层设置单词结束符
        node.isEnd = True


    def search(self, word: str) -> bool:
        # 指向根节点
        node = self
        for ch in word:
            num = ord(ch) - ord("a")
            # 如果节点的children中没有 字符,则返回 Failse
            if not node.children[num]:
                return False
            # 更新下一层节点
            node = node.children[num]
        return node.isEnd

    def startsWith(self, prefix: str) -> bool:
        node = self
        for ch in prefix:
            num = ord(ch) - ord("a")
            if not node.children[num]:
                return False
            node = node.children[num]
        # 只找前缀,把prefix遍历完即可
        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)

208. 实现 Trie (前缀树)

posted @ 2023-06-06 16:17  柳叶昶  阅读(8)  评论(0编辑  收藏  举报