[Notes] Trees - Tries(Prefix Tree,前缀树)

Posted by 西维蜀黍的OJ Blog on 2023-09-10, Last Modified on 2025-03-25

Knowledge

解析

208. Implement Trie (Prefix Tree)

  • 每个 TrieNode 节点都用一个hashmap来存储他的children,再用 一个 Bool 来保存当前字母是否为一个词的结束字符
# Prefix Tree (DPS + hashmap)
#  - time: O(n) # n is the length of the string
#  - space: O(t) # t is the total number of TrieNodes created in the Trie
class TreeNode(object):
    def __init__(self):
        self.end = False
        self.children = {}


class Trie(object):

    def __init__(self):
        self.root = TreeNode()

    def insert(self, word):
        """
        :type word: str
        :rtype: None
        """
        cur = self.root
        for c in word:
            if c not in cur.children:
                cur.children[c] = TreeNode()
            cur = cur.children[c]
        cur.end = True

    def search(self, word):
        """
        :type word: str
        :rtype: bool
        """
        cur = self.root
        for c in word:
            if c not in cur.children:
                return False
            cur = cur.children[c]
        return cur.end

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

ref

211. Design Add and Search Words Data Structure

  • 用DFS去实现回溯
class TreeNode(object):
    def __init__(self):
        self.children = {}
        self.end = False

# Prefix Tree (DPS + hashmap)
#  - time: O(n) for addWord, O(Σ^n) for search  # n is the length of the string。Σ 是字符集,这道题中的字符集为全部小写英语字母,∣Σ∣=26。
#  - space: O(∣T∣⋅∣Σ∣),其中 ∣T∣ 是所有添加的单词的长度之和,Σ 是字符集,这道题中的字符集为全部小写英语字母,∣Σ∣=26。
class WordDictionary(object):

    def __init__(self):
        self.root = TreeNode()

    def addWord(self, word):
        """
        :type word: str
        :rtype: None
        """
        cur = self.root
        for c in word:
            if c not in cur.children:
                cur.children[c] = TreeNode()
            cur = cur.children[c]
        cur.end = True

    def search(self, word):
        """
        :type word: str
        :rtype: bool
        """

        def dfs(j, root):
            cur = root
            for i in range(j, len(word)):
                c = word[i]
                if c == ".":
                    for child in cur.children.values():
                        if dfs(i + 1, child):
                            return True
                    return False
                else:
                    if c not in cur.children:
                        return False
                    cur = cur.children[c]
            return cur.end

        return dfs(0, self.root)

ref

todo - 2707. Extra Characters in a String

Ref