2026/04/17

[LeetCode] 208 Implement Trie (Prefix Tree)

 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
class Trie {
public:
  static constexpr int NODESIZE = 26;
  bool isWord;
  Trie* node[NODESIZE];

  Trie() {
    isWord = false;
    for (int i = 0; i < NODESIZE; i++)
      this->node[i] = nullptr;
  }
  
  void insert(string word) {
    if (word.empty()) {
      this->isWord = true;
      return;
    }
    int idx = word[0] - 'a';
    if (!this->node[idx])
      this->node[idx] = new Trie();
    this->node[idx]->insert(word.substr(1));
  }
  
  bool search(string word) {
    if (word.empty())
      return this->isWord;
    int idx = word[0] - 'a';
    if (!this->node[idx])
      return false;
    return this->node[idx]->search(word.substr(1));
  }
  
  bool startsWith(string prefix) {
    if (prefix.empty())
      return true;
    int idx = prefix[0] - 'a';
    if (!this->node[idx])
      return false;
    return this->node[idx]->startsWith(prefix.substr(1));
  }
};

/**
 * 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);
 */