[LeetCode] Implement Trie (Prefix Tree)

208. Implement Trie (Prefix Tree)

A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

  • Trie() Initializes the trie object.
  • void insert(String word) Inserts the string word into the trie.
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class _Trie {
private:
_Trie* t[26];
bool endOfWord;

public:
_Trie () : endOfWord(false) {
memset(t, 0, sizeof(t));
}

_Trie* insertIfAbsence(char c) {
if (t[c-'a'] == NULL) t[c-'a'] = new _Trie();
return t[c-'a'];
}

_Trie* get(char c) {
return t[c-'a'];
}

void eow() {this->endOfWord = true;}

bool getEow() { return this->endOfWord; }
};

class Trie {
_Trie* trie;
public:
/** Initialize your data structure here. */
Trie() {
this->trie = new _Trie();
}

/** Inserts a word into the trie. */
void insert(string word) {
_Trie* cur = trie;
for(int i = 0; i < word.size(); i++) {
cur = cur->insertIfAbsence(word[i]);
}
cur->eow();
}

/** Returns if the word is in the trie. */
bool search(string word) {
_Trie* cur = trie;
for(int i = 0; i < word.size() && cur; i++) {
cur = cur->get(word[i]);
}
return cur && cur->getEow();
}

/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
_Trie* cur = trie;
for(int i = 0; i < prefix.size() && cur; i++) {
cur = cur->get(prefix[i]);
}
return cur;
}
};

/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/29/PS/LeetCode/implement-trie-prefix-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.