208. 实现 Trie (前缀树)

难度:中等

实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

示例:

Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // 返回 true
trie.search(“app”); // 返回 false
trie.startsWith(“app”); // 返回 true
trie.insert(“app”);
trie.search(“app”); // 返回 true

解题思路:
前缀树又叫字典树,具体定义可以看[LeetCode] 前缀树。

python代码:

class TrieNode:
    def __init__(self) -> None:
        self.children = {}
        self.end = 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.
        """
        tree = self.root
        for w in word:
            if w not in tree.children:
                tree.children[w] = TrieNode()
            tree = tree.children[w]
        tree.end = True

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


    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        tree = self.root
        for w in prefix:
            if w not in tree.children:
                return False
            tree = tree.children[w]
        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)

复杂度分析:
(1)insert:

  • 时间复杂度 O ( m ) O(m) O(m) m m m是键长,每次迭代树的过程中,要么创建新节点要么检查是否与当前节点的值相等,直到到达键尾;
  • 空间复杂度 O ( m ) O(m) O(m):最差的情况下,新插入的键和树中已有的键没有公共前缀,新增了 m m m个节点。

(2)search:

  • 时间复杂度 O ( m ) O(m) O(m):当键的每个符号都在树中出现,会一直迭代下去,长度为键的长度 m m m
  • 空间复杂度 O ( 1 ) O(1) O(1):查找并没有增加内存。

(3)startsWith(找前缀):

  • 时间复杂度 O ( m ) O(m) O(m):当键的每个符号都在树中出现,会一直迭代下去,长度为键的长度 m m m
  • 空间复杂度 O ( 1 ) O(1) O(1):找前缀并没有增加内存。

你可能感兴趣的:(LeetCode,Trie,前缀树,字典树)