[LeetCode] Implement Trie II (Prefix Tree)

1804. Implement Trie II (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.
  • int countWordsEqualTo(String word) Returns the number of instances of the string word in the trie.
  • int countWordsStartingWith(String prefix) Returns the number of strings in the trie that have the string prefix as a prefix.
  • void erase(String word) Erases the string word from the trie.
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
68
69
70
71
72
73
74
75
76
77
78
79
80
struct PrefixTree{
int eof = 0;
int prefix = 0;
PrefixTree* next[26];

PrefixTree() {
memset(next, 0, sizeof(next));
}

void insert(string& s, int p) {
prefix++;
if(p == s.length()) eof++;
else {
if(!next[s[p]-'a']) next[s[p]-'a'] = new PrefixTree();
next[s[p]-'a']->insert(s, p + 1);
}
}

int equal(string& s, int p) {
if(p == s.length()) return eof;
if(!prefix) return 0;
if(next[s[p] - 'a']) return next[s[p] - 'a']->equal(s, p + 1);
return 0;
}

int prefixEqual(string& s, int p) {
if(p == s.length()) return prefix;
if(!prefix) return 0;
if(next[s[p] - 'a']) return next[s[p] - 'a']->prefixEqual(s, p + 1);
return 0;
}

bool remove(string& s, int p) {
if(p == s.length()) {
if(eof) {--eof; --prefix; return true;}
return false;
}
if(next[s[p] - 'a']) {
if(!prefix) return 0;
if(next[s[p] - 'a']->remove(s, p + 1)) {
--prefix;
return true;
}
return false;
}
return false;
}
};
class Trie {
PrefixTree* pt;
public:
Trie() {
pt = new PrefixTree();
}

void insert(string word) {
pt->insert(word, 0);
}

int countWordsEqualTo(string word) {
return pt->equal(word, 0);
}

int countWordsStartingWith(string prefix) {
return pt->prefixEqual(prefix, 0);
}

void erase(string word) {
pt->remove(word, 0);
}
};

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