solution.md 6.9 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1
# 实现 Trie (前缀树)
2

每日一练社区's avatar
每日一练社区 已提交
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
<p><strong><a href="https://baike.baidu.com/item/字典树/9825209?fr=aladdin" target="_blank">Trie</a></strong>(发音类似 "try")或者说 <strong>前缀树</strong> 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。</p>

<p>请你实现 Trie 类:</p>

<ul>
	<li><code>Trie()</code> 初始化前缀树对象。</li>
	<li><code>void insert(String word)</code> 向前缀树中插入字符串 <code>word</code></li>
	<li><code>boolean search(String word)</code> 如果字符串 <code>word</code> 在前缀树中,返回 <code>true</code>(即,在检索之前已经插入);否则,返回 <code>false</code></li>
	<li><code>boolean startsWith(String prefix)</code> 如果之前已经插入的字符串 <code>word</code> 的前缀之一为 <code>prefix</code> ,返回 <code>true</code> ;否则,返回 <code>false</code></li>
</ul>

<p> </p>

<p><strong>示例:</strong></p>

<pre>
<strong>输入</strong>
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
<strong>输出</strong>
[null, null, true, false, true, null, true]

<strong>解释</strong>
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
</pre>

<p> </p>

<p><strong>提示:</strong></p>

<ul>
	<li><code>1 <= word.length, prefix.length <= 2000</code></li>
	<li><code>word</code><code>prefix</code> 仅由小写英文字母组成</li>
	<li><code>insert</code><code>search</code><code>startsWith</code> 调用次数 <strong>总计</strong> 不超过 <code>3 * 10<sup>4</sup></code></li>
</ul>

每日一练社区's avatar
每日一练社区 已提交
45
<p>以下<span style="color:red">错误</span>的选项是?</p>
每日一练社区's avatar
每日一练社区 已提交
46 47

## aop
48

每日一练社区's avatar
每日一练社区 已提交
49
### before
50

每日一练社区's avatar
每日一练社区 已提交
51 52 53 54 55
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
56

每日一练社区's avatar
每日一练社区 已提交
57 58 59 60 61
```cpp

```

## 答案
62

每日一练社区's avatar
每日一练社区 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
```cpp
class TrieNode
{
public:
    bool end_with;
    TrieNode *next[26];

    TrieNode()
    {
        end_with = false;
        memset(next, 0, sizeof(next));
    }
};

class Trie
{
    TrieNode root;

public:
    /** Initialize your data structure here. */
    Trie() {}

    /** Inserts a word into the trie. */
    void insert(string word)
    {
        TrieNode *node = &root;
        for (int i = 0; i < word.size(); i++)
        {
            int c = word[i] - 'a';
            node->next[c] = new TrieNode();
            node = node->next[c];
        }
        node->end_with = true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word)
    {
        TrieNode *node = &root;
        for (int i = 0; i < word.size(); i++)
        {
            if (node->next[word[i] - 'a'] != NULL)
                node = node->next[word[i] - 'a'];
            else
                return false;
        }
        return (node->end_with) ? true : false;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix)
    {
        TrieNode *node = &root;
        for (int i = 0; i < prefix.size(); i++)
        {
            if (node->next[prefix[i] - 'a'] != NULL)
                node = node->next[prefix[i] - 'a'];
            else
                return false;
        }
        return true;
    }
};
```
## 选项

### A
```cpp
struct TrieNode
{
    bool isEnd = false;
    TrieNode *children[26] = {NULL};
};

class Trie
{
public:
    Trie() : root(new TrieNode) {}

    void insert(string word)
    {
        TrieNode *p = root;
        for (int i = 0; i < word.size(); ++i)
        {
            int idx = word[i] - 'a';
            if (p->children[idx] == NULL)
                p->children[idx] = new TrieNode;
            p = p->children[idx];
        }
        p->isEnd = true;
    }

    bool search(string word)
    {
        auto p = root;
        for (int i = 0; i < word.size(); ++i)
        {
            int idx = word[i] - 'a';
            if (p->children[idx] == NULL)
                return false;
            p = p->children[idx];
        }
        return p->isEnd;
    }

    bool startsWith(string prefix)
    {
        auto p = root;
        for (int i = 0; i < prefix.size(); ++i)
        {
            int idx = prefix[i] - 'a';
            if (p->children[idx] == NULL)
                return false;
            p = p->children[idx];
        }
        return true;
    }

private:
    TrieNode *root;
};
```

### B
```cpp
struct TrieNode
{
    const static int MaxBranchNum = 26;
    char data;
    bool isEnd = false;
    vector<TrieNode *> children = vector<TrieNode *>(26);
    TrieNode(char data) : data(data){};
};

class Trie
{
public:
    Trie() : root(new TrieNode('/')) {}

    void insert(string word)
    {
        TrieNode *p = root;
        for (int i = 0; i < word.size(); ++i)
        {
            int idx = word[i] - 'a';
            if (p->children[idx] == NULL)
                p->children[idx] = new TrieNode(word[i]);
            p = p->children[idx];
        }
        p->isEnd = true;
    }

    bool search(string word)
    {
        auto p = root;
        for (int i = 0; i < word.size(); ++i)
        {
            int idx = word[i] - 'a';
            if (p->children[idx] == NULL)
                return false;
            p = p->children[idx];
        }
        return p->isEnd;
    }

    bool startsWith(string prefix)
    {
        auto p = root;
        for (int i = 0; i < prefix.size(); ++i)
        {
            int idx = prefix[i] - 'a';
            if (p->children[idx] == NULL)
                return false;
            p = p->children[idx];
        }
        return true;
    }

private:
    TrieNode *root;
};
```

### C
```cpp
struct Node
{
    map<char, Node *> next;
    bool f = false;  
};
class Trie
{
public:
    Node *head;
    /** Initialize your data structure here. */
    Trie()
    {
        head = new Node();
    }

    /** Inserts a word into the trie. */
    void insert(string word)
    {
        Node *t = head;
        for (char c : word)
        {
            if (t->next[c] == NULL)
            {
                Node *n = new Node;
                t->next[c] = n;
            }
            t = t->next[c];
        }
        t->f = true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word)
    {
        Node *t = head;
        for (char c : word)
        {
            if (t->next[c] == NULL)
            {
                return false;
            }
            t = t->next[c];
        }
        return t->f;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix)
    {
        Node *t = head;
        for (char c : prefix)
        {
            if (t->next[c] == NULL)
            {
                return false;
            }
            t = t->next[c];
        }
        return true;
    }
};
```