实现 Trie (前缀树)

实现 Trie (前缀树)

CategoryDifficultyLikesDislikes
algorithmsMedium (64.69%)210-

Tags

design | trie

Companies

bloomberg | facebook | google | microsoft | twitter | uber

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

示例:

1
2
3
4
5
6
7
8
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

说明:

  • 你可以假设所有的输入都是由小写字母 a-z 构成的。
  • 保证所有输入均为非空字符串。

Discussion | Solution

解法

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Trie:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}  #dict 

    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        node = self.root
        for c in word:
            if not c in node.keys():
                node[c] = {}
            node = node[c]
        node["is_word"] = True

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

        if 'is_word' in node.keys():
            return True
        else:
            return False

    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        node = self.root
        for c in prefix:
            if not c in node.keys():
                return False
            node = node[c]

        return True
  • rust
1

updatedupdated2024-11-232024-11-23