0208._implement_trie_(prefix_tree).md 2.5 KB
Newer Older
1
# 208. Implement Trie (Prefix Tree)
2

3
**<font color=orange>难度: Medium</font>**
4

5
## 刷题内容
6

7
> 原题连接
8

9
* https://leetcode.com/problems/implement-trie-prefix-tree/
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
> 内容描述

```

Implement a trie with insert, search, and startsWith methods.

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true
Note:

You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

这个Python实现也太精美了吧,谷歌复写之

然后还unlock了一个solution,to read

Trie整个都需要 to read,精美,可爱😊




```python
class TrieNode(object):
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.childs = dict()
        self.isWord = False
        
        

class Trie(object):

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

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        node = self.root
        for letter in word:
            child = node.childs.get(letter)
            if child is None:
                child = TrieNode()
                node.childs[letter] = child
            node = child
        node.isWord = True

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        node = self.root
85 86 87
        for i in word:
            child = node.childs.get(i)
            if child is None:
88
                return False
89
            node = child
90 91 92 93 94 95 96 97 98 99 100 101
        return node.isWord
        

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie
        that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        node = self.root
        for letter in prefix:
102 103
            child = node.childs.get(letter)
            if child is None:
104
                return False
105
            node = child
106 107 108 109 110 111 112 113
        return True
        

# Your Trie object will be instantiated and called as such:
# trie = Trie()
# trie.insert("somestring")
# trie.search("key")
        
K
KEQI HUANG 已提交
114
```
115