Skip to content

1804. Implement Trie II (Prefix Tree) 👍

  • Time:
  • Space:
 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
struct TrieNode {
  vector<shared_ptr<TrieNode>> children;
  int prefixCount = 0;
  int wordCount = 0;
  TrieNode() : children(26) {}
};

class Trie {
 public:
  void insert(string word) {
    shared_ptr<TrieNode> node = root;
    for (const char c : word) {
      const int i = c - 'a';
      if (node->children[i] == nullptr)
        node->children[i] = make_shared<TrieNode>();
      node = node->children[i];
      ++node->prefixCount;
    }
    ++node->wordCount;
  }

  int countWordsEqualTo(string word) {
    shared_ptr<TrieNode> node = find(word);
    return node ? node->wordCount : 0;
  }

  int countWordsStartingWith(string prefix) {
    shared_ptr<TrieNode> node = find(prefix);
    return node ? node->prefixCount : 0;
  }

  void erase(string word) {
    shared_ptr<TrieNode> node = root;
    for (const char c : word) {
      const int i = c - 'a';
      node = node->children[i];
      --node->prefixCount;
    }
    --node->wordCount;
  }

 private:
  shared_ptr<TrieNode> root = make_shared<TrieNode>();

  shared_ptr<TrieNode> find(const string& s) {
    shared_ptr<TrieNode> node = root;
    for (const char c : s) {
      const int i = c - 'a';
      if (node->children[i] == nullptr)
        return nullptr;
      node = node->children[i];
    }
    return node;
  }
};
 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
class TrieNode {
  public TrieNode[] children = new TrieNode[26];
  public int prefixCount = 0;
  public int wordCount = 0;
}

class Trie {
  public void insert(String word) {
    TrieNode node = root;
    for (final char c : word.toCharArray()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        node.children[i] = new TrieNode();
      node = node.children[i];
      ++node.prefixCount;
    }
    ++node.wordCount;
  }

  public int countWordsEqualTo(String word) {
    TrieNode node = find(word);
    return node == null ? 0 : node.wordCount;
  }

  public int countWordsStartingWith(String prefix) {
    TrieNode node = find(prefix);
    return node == null ? 0 : node.prefixCount;
  }

  public void erase(String word) {
    TrieNode node = root;
    for (final char c : word.toCharArray()) {
      final int i = c - 'a';
      node = node.children[i];
      --node.prefixCount;
    }
    --node.wordCount;
  }

  private TrieNode root = new TrieNode();

  private TrieNode find(final String s) {
    TrieNode node = root;
    for (final char c : s.toCharArray()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        return null;
      node = node.children[i];
    }
    return node;
  }
}